|
|
写一个通用的程序pipe,它使用两个程序的名字作为参数,例如pipe who sort pipe ls sort等,程序的逻辑如下所示:
child
close(p[0])
dup2(p[1],1)
close(p[1])
exec "ls"
parent
close(p[1])
dup2(p[0],0)
close(p[0])
exec "sort"
我不明白为什么在子进程中要先关闭p[0],在父进程中要先关闭p[1],有的书上说不用的管道描述符关掉不会出错,但是我不明白不关掉会不会出现其他问题,关闭不用的管道描述符还有没有其他原因,恳请各位高手指教!下面是程序的代码,在源程序中我把子进程中的close(p[0])和父进程中的close(p[1])注释掉了,程序运行出现了问题,达不到所要求的目的,不知道为什么会出现这样的错误,还请高手分析一下原因,多谢了!
#include <stdio.h>
#include <unistd.h>
#define oops(m,x) { perror(m); exit(x); }
main(int ac, char **av)
{
int thepipe[2], /* two file descriptors */
newfd, /* useful for pipes */
pid; /* and the pid */
if ( ac != 3 ){
fprintf(stderr, "usage: pipe cmd1 cmd2\n");
exit(1);
}
if ( pipe( thepipe ) == -1 ) /* get a pipe */
oops("Cannot get a pipe", 1);
/* now we have a pipe, now let's get two processes */
if ( (pid = fork()) == -1 ) /* get a proc */
oops("Cannot fork", 2);
/* Right Here, there are two processes */
/* parent will read from pipe */
if ( pid > 0 ){ /* parent will exec av[2] */
//close(thepipe[1]); /* parent doesn't write to pipe */
if ( dup2(thepipe[0], 0) == -1 )
oops("could not redirect stdin",3);
close(thepipe[0]); /* stdin is duped, close pipe */
//close(0);
execlp( av[2], av[2], NULL);
oops(av[2], 4);
}
/* child execs av[1] and writes into pipe */
//close(thepipe[0]); /* child doesn't read from pipe */
if ( dup2(thepipe[1], 1) == -1 )
oops("could not redirect stdout", 4);
close(thepipe[1]); /* stdout is duped, close pipe */
//close(1);
execlp( av[1], av[1], NULL);
oops(av[1], 5);
} |
|