对于一些经验丰富的程序员来说,这可能是微不足道的,但是在流水线化(或者考虑这样做)多个程序之后,我被困在这里没有任何输出。
问题需要父进程开始通过管道向其第一个子进程提供数据,这些子进程按以下方式顺序执行到进程列表:
Father -> 1st Child -> 2nd -> 3rd -> ... -> stdout.
所有流程都是Father
的孩子。
现在我拥有我认为工作代码的东西,但是一旦队列中有多个程序,它就会停止工作,经过多次查看和重新编码后,我无法正常工作。
这就是我正在使用的,减去错误检查代码:
int pipes[proc_number][2], i = 0;
for (; i < proc_number; ++i) {
pipe(pipes[i]);
}
int current = 0;
bool first = true, last = false;
while (current != proc_number) {
last = current == proc_number - 1;
int pid = fork();
// Child code:
if (pid == 0) {
// We always need to pipe stdin:
dup2(pipes[current][0], STDIN_FILENO);
// But only the last one doesn't need to pipe stdout:
if (!last) {
dup2(pipes[current + 1][1], STDOUT_FILENO);
}
// Close the array of pipes:
for (i = 0; i < proc_number; ++i) {
close(pipes[i][0]);
close(pipes[i][1]);
}
// Exec the process:
execlp(proc[current], proc[current], NULL);
exit(5);
// Father code:
} else if (pid > 0){
// The father process needs to pipe its output to the first child only:
if (first) {
dup2(pipes[current][1], STDOUT_FILENO);
}
// Fork didn't work:
} else {
exit(6);
}
// Not first child anymore:
first = false;
// Advance to next:
++current;
}
// Finally close all pipes in the father process:
for (i = 0; i < proc_number; ++i) {
close(pipes[i][0]);
close(pipes[i][1]);
}
有没有人知道这里发生了什么?只要只有一个孩子,它就可以正常工作。如果有更多,进程正在等待管道...
从图形上看,我想要完成的是这样的(假设有2个孩子):
Pipe0: 1st child input O====O father output
Pipe1: 2nd child input O====O 1st child out
2nd child output unredirected, ends up in stdout.