进程通信——管道

在父进程中用pipe()建立一条管道线,往管道里写一句话,两个子进程接收这句话。

 1 #include
 2 #include
 3 #include
 4 #include
 5 #include
 6 int pid1,pid2;
 7 int main()
 8 {
 9     int fd[2];
10     char OutPipe[100],InPipe[100];
11   pipe(fd);
12      while((pid1=fork())==-1);
13      if(pid1==0)
14   { 
15      lockf(fd[1],1,0);
16      sprintf(OutPipe,"child 1 process is sending message!");
17      write(fd[1],OutPipe,50);
18      sleep(5);
19      lockf(fd[1],0,0);
20      exit(0);
21    }
22      else
23   {
24           while((pid2=fork())==-1);
25           if(pid2==0)
26      { 
27        lockf(fd[1],1,0);
28        sprintf(OutPipe,"child 2 process is sending message!");
29        write(fd[1],OutPipe,50);
30        sleep(5);
31        lockf(fd[1],0,0);
32        exit(0);
33       }
34           else
35      {
36        wait(0);
37        read(fd[0],InPipe,50);
38        printf("%s\n",InPipe);
39        wait(0);
40        read(fd[0],InPipe,50);
41        printf("%s\n",InPipe);
42        exit(0);
43      }
44   }
45 }

 

#include
#include
#include
#include
#include
int pid1,pid2;
int main()
{
    int fd[2];
    char OutPipe[100],OutPipe1[100],InPipe[100];
  pipe(fd);
     while((pid1=fork())==-1);
     if(pid1==0)
  { 
    //   wait(0);
       read(fd[0],InPipe,50);
       printf("pid1:\n%s\n",InPipe);     
exit(0);
// 
   }
     else
  {
          while((pid2=fork())==-1);
          if(pid2==0)
     {
       wait(0);
       read(fd[0],InPipe,50);
       printf("pid2:\n%s\n",InPipe);
       exit(0);
//
      }
          else
     {
     lockf(fd[1],1,0);
     sprintf(OutPipe,"child 1 process is sending message!");
     write(fd[1],OutPipe,50);
     sleep(1);
     lockf(fd[1],0,0); 
     sprintf(OutPipe1,"child 2 process is sending message!");
     write(fd[1],OutPipe1,50);
     exit(0);
//   
     }
  }
}

进程通信——管道_第1张图片

 

你可能感兴趣的:(进程通信——管道)