进程通信——管道

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

 1 #include<unistd.h>
 2 #include<signal.h>
 3 #include<stdio.h>
 4 #include<stdlib.h>
 5 #include<sys/wait.h>
 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<unistd.h>
#include<signal.h>
#include<stdio.h>
#include<stdlib.h>
#include<sys/wait.h>
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);
//   
     }
  }
}

 

posted @ 2018-08-30 18:01  王义强  阅读(888)  评论(0编辑  收藏  举报