Pipe implementation

為{幸葍}努か 提交于 2019-11-28 09:20:19

You need to replace one child's stdout with the writing end of the pipe, and the other child's stdin with the reading end:

if (pid == 0)  
{  
   close(fd[0]); //close read from pipe, in parent
   dup2(fd[1], STDOUT_FILENO); // Replace stdout with the write end of the pipe
   close(fd[1]); // Don't need another copy of the pipe write end hanging about
   execlp("cat", "cat", "names.txt", NULL);
}
else
{
   close(fd[1]); //close write to pipe, in child
   dup2(fd[0], STDIN_FILENO); // Replace stdin with the read end of the pipe
   close(fd[0]); // Don't need another copy of the pipe read end hanging about
   execlp("sort", "sort", NULL);
} 

Look into the pipe() standard library call. This is used to create a pipe. You must of course do part of the work before you fork(), in order for the child process to inherit the file descriptor properly.

Also note the order of the arguments to dup2():

int dup2(int oldfd, int newfd);

dup2() makes newfd be the copy of oldfd, closing newfd first if necessary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!