C program demonstrating use of pipe system call in linux (sending message from child process to parent process)
#include <sys/wait.h>#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <string.h>intmain(int argc, char *argv[]){int pipefd[2];pid_t cpid;char buf[30];if (pipe(pipefd) == -1) {printf("pipe error");exit(EXIT_FAILURE);}cpid = fork();if (cpid == -1) {printf("fork error");exit(EXIT_FAILURE);}if (cpid == 0) { /* Child reads from pipe */char buffer2[30]="message from child";printf("nnNow in child processn");close(pipefd[0]); /* Close unused write end */write(pipefd[1], buffer2, sizeof(buffer2));close(pipefd[1]);_exit(EXIT_SUCCESS);} else {printf("nnNow in parent process n");wait(NULL);close(pipefd[1]); /* Close unused read end */read(pipefd[0], buf, sizeof(buf));printf("nnNow again in parent process n");printf("nn%snn",buf);close(pipefd[0]);/* Wait for child */exit(EXIT_SUCCESS);}}
Output :
dell@linuxmint ~ $ gcc pipe.c
dell@linuxmint ~ $ ./a.out
Now in parent process
Now in child process
Now again in parent process
message from child
Comments
Post a Comment