[英]Piping in a basic shell implementation
In an assignment we were asked to implement piping. 在一项作业中,我们被要求实施管道。 I was able to do so, but the problem which I am encountering is that when I enter the command
我能够这样做,但是遇到的问题是当我输入命令时
ls |
ls | grep 'a.out'
grep'a.out'
then the output is 那么输出是
a.out
出
a.out
出
but when I do 但是当我这样做
ls |
ls | wc
厕所
The output comes only once. 输出只有一次。 Can anyone point out the mistake in the code ?.
谁能指出代码中的错误? The code is as follows :
代码如下:
void execute_pipe(char **argv,char **args)
{
int pfds[2];
pid_t pid,pid2;
int status,status2;
pipe(pfds);
if ((pid = fork()) < 0) {
printf("*** ERROR: forking child process failed\n");
exit(1);
}
if ((pid2 = fork()) < 0) {
printf("*** ERROR: forking child process failed\n");
exit(1);
}
if (pid==0) {
close(1);
dup(pfds[1]);
close(pfds[0]);
close(pfds[1]);
if(execvp(argv[0],argv)<0){
printf("**error in exec");
}
}
else if(pid2==0){
close(0);
dup(pfds[0]);
close(pfds[1]);
close(pfds[0]);
if(execvp(args[0],args)<0){
printf("**error in exec");
}
}
else{
close(pfds[0]);
close(pfds[1]);
while (wait(&status) != pid) ;
while (wait(&status2) != pid2) ;
}
}
I ma quite sure that there are no stray prints and there is only one a.out in the directory. 我可以肯定没有杂散打印,并且目录中只有一个a.out。
You run the second fork
in both the parent and first child processes. 您在父进程和第一个子进程中都运行第二个
fork
。 You should only do the second fork if pid
is non-zero. 如果
pid
不为零,则只应执行第二个派生。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.