Understanding Unix Pipes
November 4 by Bina
Pipes demo code
Motivation & Purpose
You created new processes using fork() system call
You delegated work to the newly created process using exec() system call
How can communicate between processes?
For sending messages and data? pipe() system call
For signaling /interrupting each other? kill() system call
In this lecture we will study pipe() in and kill() and signals in the next week
Pipe() call Details
Pipes are kernel level data flow mechanisms
It is an anonymous storage with two pointer, one to write into the pipe and another to read from
When a pipe() call is invoked, control traps to the kernel, creates the storage for the pipe and returns with the two pointer call descriptors of “int” type.
The pointers are the returned in a array parameter to the pipe() call.
It also returns a negative value in case the call failed, 0 for success.
Creating a Pipe
int fd[2];
int retVal;
retVal= pipe(fd);
if (retVal < 0) printf(“error”);
else
{
write(fd[1],….
read(fd[0],…
Pipe Demos
Demo Code
We will look at other examples in the demo directory
- Simple pipe
- Fork and pipe for communication, file table
- Multiple pipe as discussed in the code below
- Pipes as discussed in one of the references
- Also look at dup(), dup2() system calls for redirection of IO, files and pipes()
Summary
- fork(): to create a new process
- exec(): to overlay a code for execution in process
- wait(): to wait for a process
- pipe(): to create pipe for communication within an addresses space
- dup() and dup2(): to redirect file descriptors
Code Example
int main() {
pid_t newpid;
int fd1[2], fd2[2];
char m1[] = "Minecraft Playbook\n";
char m2[] = "Assemble Silver lining\n";
char rbuf1[256];
char rbuf2[256];
int cn1, cn2;
if ((pipe(fd1)== -1)) printf(" error \n");
printf("fd1 %d %d \n", fd1[0], fd1[1]);
dup(fd1[0]);
dup(fd1[1]); //#1 show the open file descriptor table here
write(4, m1, sizeof(m1));
cn1 = read(5, rbuf1, 256);
write(1, rbuf1, cn1); //#2 show the structure of pipe fd1 with the respect the current process
if ((pipe(fd2)== -1)) printf(" error \n");
printf("fd2 %d %d \n", fd2[0], fd2[1]);
if ((newpid = fork()) == -1) { printf("error \n"); return 0;}
if (newpid >0 )
{ //parent
write(4, m2, sizeof(m2)); //#3 show the open file descriptor table here
}
else { //child
cn2 = read(3, rbuf2, 256);
write(1, rbuf2,cn2);
int fd3[2];
if ((pipe(fd3)== -1)) printf(" error \n");
printf("fd3 %d %d \n", fd3[0], fd3[1]); //#4 Show the open file descriptor table for parent + child
// other code
}
return 0; }