Thursday, November 12, 2015

Using pipe() command in Linux

 #include<unistd.h>  
 #include<stdio.h>  
 main()  
 {  
 int pid;        //storing process id in case of fork  
 char str[15];      //array used to input string in parent  
 char str2[15];     //array for receiving string in child  
 int pipeArray[2];    //pipe file descripter 'pipeArray[0] = end of pipe used to read' and 'pipeArray[1] = end of pipe used to write'  
 if(pipe(pipeArray)==-1) //error in creating pipe  
     {  
     printf("\nError\n");  
     exit(0);  
     }  
 pid=fork();       //forking initiating parent and child  
 if(pid==-1)       //error in fork  
     printf("\nError\n");  
 else if(pid==0)     //pid=0 means child  
     {  
     //child  
     close(pipeArray[1]);      //close write file descripter as we will only be reading  
     read(pipeArray[0],str2,15);   //read from file descripter, use 'man 2 read' command in linux to understand it  
     close(pipeArray[0]);      //closing read pipe after use  
     printf("\nI am the famous Child -%s",str2);   }  
 else  
     {  
     //parent  
     close(pipeArray[0]);      //close read fd  
     printf("\nenter String\n");  
     scanf("%s",str);  
     write(pipeArray[1],str,15);   //write to file descriptr  
     close(pipeArray[1]);      //close write pipe after use  
     wait();             //wait for child process to complete  
     }  
 }  

No comments:

Post a Comment