首页 > 代码库 > Linux_C 进程间共享管道
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 }
Linux_C 进程间共享管道
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。