Write a C program to create a unnamed pipe

Viewed 1781

Write a C program which is used to create unnamed pipe. Parent process creates a new child process and both the processes will communicate with each other.

Solution that I have tried.

Is this the right way to make use of unnamed pipe?

 #include<stdio.h>
 #include<unistd.h>
 #include<string.h>
 
 int main() {
     int fd[2] , ret = 0;
     char buffer[] = "Marvellous InfoSystems";
     char readBuff[BUFSIZ];
     pid_t Childpid;
 
     pipe(fd);                                           //create a oneway communication channel i.e pipe i.e unnamed pipe
 
     Childpid = fork();
 
     if(Childpid == 0)                                   //child process
     {
         close(fd[0]);                                   /*close the ipnut side of the pipe after entering the child process*/
         printf("Child intiaites communication by writing the data at output side of the pipe \n");
         write(fd[1] , buffer , sizeof(buffer));         /*Child process writes at the output side of the pipe*/
     }
     else                                                //parent process
     {
         close(fd[1]);                                   /*Close output side of the pipe after the entering the parent proces*/
         ret = read(fd[0] , readBuff , sizeof(readBuff));/*Parent proces reads the data i.e written by the child at output side of the
 pipe*/
         printf("The data read by Parent process is : %s \n",readBuff);
     }
 
     return 0;
}
0 Answers
Related