Linux_C 进程间共享管道

程序pipe, 它使用可例如: ./pipe who sort   ./pipe ls head

 1 /* pipe.c
 2  * Demostrates how to create a pipeline from one process to another
 3  * * take two args, each a command ,and connects
 4  *   argv[1]s output to intput of argv[2]
 5  *   effect: command1 | command2
 6  */
 7 #include <stdio.h>
 8 #include <unistd.h>
 9 
10 #define oops(x,n) { perror(x); exit(n); }
11 
12 int main(int argc, char *argv[]){
13   int pid, thepipe[2];
14   if(argc!=3) {
15     fprintf(stderr, "usage: pipe cmd1 cmd2.\n");
16     exit(1);
17   }
18   if(pipe(thepipe) == -1)
19     oops("pipe", 2);
20   if((pid=fork()) == -1)
21     oops("fork", 3);
22   if(pid==0) {                  /*child execs argv[1] and writes into pipe*/
23     close(thepipe[0]);          /*      child doesnt read from pipe       */
24     if((dup2(thepipe[1], 1)) == -1)     /*child change the stdout, set the stdout into the pipe*/
25       oops(argv[1], 6);
26     close(thepipe[1]);          /*stdout is duped , close pipe*/
27     execlp(argv[1], argv[1], NULL);
28     oops("child", 4);
29   }else if(pid>0) {             /*parent execs argv[0] and read from pipe*/
30     close(thepipe[1]);          /*     parent doesnt write to pipe       */
31     if(dup2(thepipe[0], 0) == -1)
32       oops("could not redirect stdin", 6);
33     close(thepipe[0]);          /*     stdin is duped, close pipe        */
34     execlp(argv[2],argv[2], NULL);
35     oops(argv[2], 5);
36   }
37   return 0;
38 }

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。