如何实现多个流程的管道?

mms*_*swe 2 c unix linux pipe process

我正在创建多个进程,我需要为每个进程创建两个未命名的管道.

对于每个子节点,将使用一个管道从父节点获取int值; 一个用于将int数组发送到父数组.家长会从孩子那里获取新数据时做一些事情.

基本代码:

#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h> // for reaching unix operations


int main(int argc, char *argv[]){
    pid_t main = getpid();

    int N = 30;
    int i;
    pid_t* children = (pid_t*) malloc(sizeof(pid_t) * N);
    for(i = 0; i < N; i++){
        pid_t child = fork();
        if ( child == 0){
            pid_t me = getpid();
            printf("I'm a child and my pid is: %d\n", me);
             sleep(1);
            // exit(4);
            return me * 2;
        } else if ( child < 0){
            // printf("Could not create child\n");
        } else {
            children[i] = child;
            // printf("I have created a child and its pid %d\n", child);
        }
    }

    // The child never reaches here
    for(i = 0; i < N; i++){
        int status;
        waitpid(children[i], &status, 0);
        printf("Process %d exited with return code %d\n", children[i], WEXITSTATUS(status));
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我尝试了许多没有成功的事情,我迷路了.你能帮我继续吗?

任何帮助表示赞赏!谢谢.

Dan*_*ein 10

以下是如何为每个子进程设置一个管道,以便每个子进程写入父进程:

由于每个子项需要两个文件描述符,因此声明:

int fd[2 * N];
Run Code Online (Sandbox Code Playgroud)

适当地初始化它们:

for (int i = 0; i < N; i++) {
    pipe(&fd[2*i]);
}
Run Code Online (Sandbox Code Playgroud)

i-th子进程中,使用:

write(fd[2*i + 1], write_buffer, SIZE) 
Run Code Online (Sandbox Code Playgroud)

写入父级,并在父级中使用:

 read(fd[2*i], read_buffer, SIZE) 
Run Code Online (Sandbox Code Playgroud)

从第 - i个孩子读.


关闭管道:

i第一个孩子里面,你可以使用

close(fd[2*i]) 
Run Code Online (Sandbox Code Playgroud)

马上,看到你只是在写作.你写完电话后

close(fd[2*i + 1]) 
Run Code Online (Sandbox Code Playgroud)

关闭管道的写入端.

父母的情况是平行的:当i你从第一个孩子读书时,你可以

close(fd[2*i + 1]) 
Run Code Online (Sandbox Code Playgroud)

马上,因为你没有写作,并且在你完成阅读电话之后

close(fd[2*i])
Run Code Online (Sandbox Code Playgroud)

关闭管道的读取端.


由于每个子进程需要两个管道,因此创建两个数组 - 一个包含用于写入父项的子项的管道,另一个包含用于写入子项的父项的管道.