它所创建的管道等价于下面的shell管道:$echo good morning|sed s/good/hi/g该程序的实现过程是:调用pipe()建立一个管道,利用fork()创建两个子进程;一个是左侧进程,另一个是右侧进程。左侧进程使用close(pipefd[0])关闭管道读取端,使用close(1)关闭最初的标准输出,使用dup(pipefd[1])将管道的写入端改为文件描述符1,使用close(pipefd[1])关闭打开文件描述符的一个副本,调用execvp()启动运行的程序;右侧进程的工作于此相似:使用close(pipefd[1])关闭管道写入端,使用close(0)关闭最初的标准输入,使用dup(pipefd[0])将管道的读取端改为文件描述符0,使用close(pipefd[0])关闭打开文件描述符的一个副本,调用execvp()启动运行程序。在父进程中,关闭管道的两端:close(pipefd[0])和close(pipefd[1]).最后,在父进程中使用wait()等待两个子进程结束。
#include <stdio.h> #include <unistd.h> #include <stdlib.h> int main() { int pid1, pid2; int pfd[2]; pipe(pfd); pid1 = fork(); if (pid1 == 0) { char * argv[] = { "echo", "good morning", NULL }; /* left child */ close(pfd[0]); close(1); /* close stdout */ dup(pfd[1]); /* redirect stdout to pipe */ close(pfd[1]); execvp("echo", argv); exit(1); } pid2 = fork(); if (pid2 == 0) { char *argv[] = { "sed", "s/good/hi/g", NULL }; /* right child */ close(pfd[1]); close(0); /* close stdin */ dup(pfd[0]); /* redirect stdin to pipe */ close(pfd[0]); execvp("sed", argv); exit(1); } close(pfd[0]); close(pfd[1]); wait(NULL); wait(NULL); printf("Both children exited.\n"); return 0; }
转载请注明原文地址: https://www.6miu.com/read-79736.html