Pipe()fork()和exec
问题描述:
我尝试在迷你外壳中添加管道。 当我输入ls |时,我很困惑排序,没有显示,我不明白为什么:我不明白为什么:Pipe()fork()和exec
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);
}
}
我已阅读所有关于该主题,但它不起作用。 你能帮我吗?
编辑:第二个代码,我尝试改变结构。
谢谢。
答
第二个fork
不会在execvp
成功的情况下被达到,因为后者应该替换进程的映像并停止执行当前代码。
你必须重组你的程序。
看看http://*.com/questions/5953386/writing-to-child-process-file-descriptor/5954324#5954324 – 2011-06-02 20:39:37
检查系统调用的错误 - 你至少dup_'ing一个close'd fd在一个点上。什么是“mot”?我*猜测*是你的execvp参数不正确。 – pilcrow 2011-06-02 20:42:23
@pilcrow,我编辑了代码,mot是命令行给出的命令。 – lilawood 2011-06-03 06:55:19