In this chapter we shall learn about:
1. Syntax for “pipe()”
2. How to create a pipe fd?
3. How to fork a new child process?
4. How to transfer data from Parent and Child proces?
5. A full example for half duplex pipe using pipe() system call.
Syntax for “pipe()”
int pipe(int fd[2]);
Here:
pipe() returns 0 on success
-1 on failure and sets errno accordingly.
fd[0] is opened for reading
fd[1] for writing.
The output of fd1 becomes the input for fd0.
How to create a pipe fd?
#include <stdio.h> #include <unistd.h> #include <sys/types.h> main() { int fd[2]; pipe(fd); . . }
How to fork a new child process?
#include <stdio.h> #include <unistd.h> #include <sys/types.h> main() { int fd[2]; pid_t childpid; pipe(fd); if((childpid = fork()) == -1) { perror("fork"); exit(1); } . . }
Here fd is equivalent to &fd[0].
How to transfer data from Parent and Child proces?
For the parent wants to receive data from the child, parent should close fd1, and the child should close fd0.
And if the parent wants to send data to the child, it should close fd0, and the child should close fd1.
#include <stdio.h> #include <unistd.h> #include <sys/types.h> main() { int fd[2]; pid_t childpid; pipe(fd); if((childpid = fork()) == -1) { perror("fork"); exit(1); } if(childpid == 0) { /* Child process closes up input side of pipe */ close(fd[0]); } else { /* Parent process closes up output side of pipe */ close(fd[1]); } . . }
A full example for half duplex pipe using pipe() system call.
#include <stdio.h> #include <unistd.h> #include <stdlib.h> //for more tutorial visit www.prodevelopertutorial.com #include <string.h> #include <sys/types.h> int main(void) { int fd[2], nbytes; pid_t childpid; char string[] = "Hello, Prodevelopertutorial!\n"; char readbuffer[80]; pipe(fd); //create a child process if((childpid = fork()) == -1) { perror("fork"); exit(1); } //close the input pipe of child process if(childpid == 0) { /* Child process closes up input side of pipe */ close(fd[0]); /* Send "string" through the output side of pipe */ write(fd[1], string, (strlen(string)+1)); exit(0); } else { /* Parent process closes up output side of pipe */ close(fd[1]); /* Read in a string from the pipe */ nbytes = read(fd[0], readbuffer, sizeof(readbuffer)); printf("Received string: %s", readbuffer); } return(0); }