Tuesday, November 11, 2014

Unix Prog: IPC Pipe(3)

1. Example:
pipe.c:
 #include<stdio.h>  
 #include<stdlib.h>  
 #include<unistd.h>  
   
 int pfd1[2], pfd2[2];  
   
 void TELL_WAIT(void)  
 {  
  // Create two pipes here, one for parent -> child  
  // another one for child -> parent  
  if(pipe(pfd1) < 0 || pipe(pfd2) < 0) {  
   printf("pipe error!\n");  
   exit(1);  
  }  
 }  
   
 void TELL_PARENT(pid_t pid)  
 {  
  if(write(pfd2[1], "c", 1) != 1) {  
   printf("write error!\n");  
   exit(2);  
  }  
 }  
   
 void WAIT_PARENT(void)  
 {  
  char c;  
   
  if(read(pfd1[0], &c, 1) != 1) {  
   printf("read error!\n");  
   exit(3);  
  }  
   
  if(c != 'p') {  
   printf("WAIT_PARENT: incorrect data");  
   exit(4);  
  }  
 }  
   
 void TELL_CHILD(pid_t pid)  
 {  
  if(write(pfd1[1], "p", 1) != 1) {  
   printf("write error!\n");  
   exit(2);  
  }  
 }  
   
 void WAIT_CHILD(void)  
 {  
  char c;  
   
  if(read(pfd2[0], &c, 1) != 1) {  
   printf("read error!\n");  
   exit(3);  
  }  
   
  if(c != 'c') {  
   printf("WAIT_CHILD: incorrect data");  
   exit(4);  
  }  
 }  
   
 int main(int argc, char* argv[])  
 {  
  exit(0);  
 }  

Description:
Besides using signal mechanism, we can also use pipes to implement the parent/child process synchronization facility. It creates 2 pipes, one for parent sending data to child, one for child sending data to parent. Following diagram can illustrate this.

No comments:

Post a Comment