我尝试在迷你 shell 中添加管道。 我很困惑,当我输入 ls |排序,什么都不显示,我不明白为什么:
int fd[2];
if (tube == 1){
int pipeling = pipe(fd);
if (pipeling == -1){
perror("pipe") ;
}
}
tmp = fork(); //FORK A
if (tmp < 0){
perror("fork");
continue;
}
if (tmp != 0) { //parent
while(wait(0) != tmp) ;
continue ;
}
if (tube == 1) { //there is a pipe
if (tmp != 0){ //parent A
close(fd[1]);
}
if (tmp == 0){ //Child A
close(fd[0]);
dup2(fd[1], 1);
close(fd[1]);
execv(mot[0], mot);
}
int tmp2 = fork() ; //FORK B
if (tmp2 != 0) { //Parent B
close(fd[0]);
while(wait(0) != tmp2) ;
continue ;
}
if (tmp2 == 0){ //Child B
close(fd[1]);
dup2(fd[0], 0);
close(fd[0]);
execvp(mot[1], mot);
}
}
我已经阅读了所有相关主题,但它不起作用。 你能帮帮我吗?
编辑:第二个代码,我尝试改变结构。
谢谢。
最佳答案
如果 execvp
成功,则不会到达第二个 fork
,因为后者应该替换进程的镜像并将停止执行当前代码。
你必须重组你的程序。
关于c - Pipe() fork() 和 exec,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6220055/