我正在嘗試製作一個分叉一次的程序,而當父級等待子進程終止時,此子進程再次分叉,然後執行兩個可執行程序。程序中有一個Pipe,我已經檢查過程序中每個dup2()和pipe()的返回值 - 在這裏省略它們使它看起來更簡潔。問題是我只能得到ls -a |的結果在程序完成後排序-r。 的代碼是:在分支進程之後執行不會返回結果在程序結束之前
#include <cstdio>
#include <cstring>
#include <sys/wait.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
int main(int argc, char *argv[]) {
printf("Shell> \n"); fflush(stdout);
pid_t pid1;
pid_t pid2;
int status = 0;
int fd[2];
if(pipe(fd) < 0) {
printf("FATAL ERROR.\n");
}
pid1 = fork();
if(pid1 > 0) { // Parent
waitpid(pid1, &status, 0);
printf("\t\t------PID1 Complete-------\n\n");
}
else { // Child
if(pid1 == 0) {
printf("ON CHILD\n");
pid2 = fork();
if(pid2 > 0) { // Child -> Parent
printf("ON CHILD-Parent\n");
close(fd[1]);
dup2(fd[0], STDIN_FILENO);
waitpid(pid2, &status, 0);
printf("ON CHILD-Parent after wait\n");
execlp("sort", "sort", "-r", NULL);
perror("Problem with execlp\n");
exit(1);
}
else { // Child -> Child
printf("ON CHILD->Child\n");
close(fd[0]);
dup2(fd[1], STDOUT_FILENO);
execlp("ls", "ls", "-a", NULL);
perror("Problem with execvp\n");
exit(1);
}
} // End of if(pid1 == 0)
} // End of Child
printf("\nEnd of program.\n");
return 0;
}
我的電流輸出爲:
Shell>
ON CHILD
ON CHILD-Parent
ON CHILD->Child
ON CHILD-Parent after wait
我認爲這個問題是在等待,但我只是無法弄清楚如何使這項工作。有任何想法嗎?謝謝!
我相信int fd [2];包含fd [0] == 0,fd [1] == 0,因爲它從不分配。然後你去關閉fd [1]並期望fd [0]工作。這可能是你的問題的原因。 – 2015-02-05 20:17:14
我可以在沒有雙分叉的情況下使用同樣的想法,所以我不確定它是否真的存在問題......我認爲我的程序由於wait()而等待「永遠」。 – Xaphanius 2015-02-05 20:38:08
@Robert:當'fd'指針傳遞給'pipe(fd)'時,'fd'的內容被賦值。 – nategoose 2015-02-05 20:57:45