Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/28.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 如何使用多个管道将当前进程与进程队列通信?_C_Linux_Pipe - Fatal编程技术网

C 如何使用多个管道将当前进程与进程队列通信?

C 如何使用多个管道将当前进程与进程队列通信?,c,linux,pipe,C,Linux,Pipe,这对一些经验丰富的程序员来说可能微不足道,但我被困在这里,在管道化或考虑执行多个程序之后,没有任何输出 该问题要求父进程开始通过管道将数据传送到其第一个子进程,该子进程将按照以下方式按顺序传送到进程列表: Father -> 1st Child -> 2nd -> 3rd -> ... -> stdout. 所有的过程都是父亲的孩子 现在我有了我认为可以工作的代码,但实际上只要队列中有多个程序,它就会停止工作,并且在查看和重新编码几次之后,我无法让它正常工作 这就

这对一些经验丰富的程序员来说可能微不足道,但我被困在这里,在管道化或考虑执行多个程序之后,没有任何输出

该问题要求父进程开始通过管道将数据传送到其第一个子进程,该子进程将按照以下方式按顺序传送到进程列表:

Father -> 1st Child -> 2nd -> 3rd -> ... -> stdout.
所有的过程都是父亲的孩子

现在我有了我认为可以工作的代码,但实际上只要队列中有多个程序,它就会停止工作,并且在查看和重新编码几次之后,我无法让它正常工作

这就是我正在使用的,减去错误检查代码:

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]);
}
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.