您可以选择哪个 child 进程从 parent 接收消息吗?

Can you choose which child process receives a message from a parent?

下面我有一个 parent 进程的代码,它创建了属于它的两个 child 进程。 现在,我知道我可以做到 parent 可以写入 child 进程,而 child 进程可以使用 read() 和 write() 从中读取。

我的问题是,parent 是否可以在下面的代码中选择向 child 写入?例如,我询问程序的用户是否想用他们自己提供的消息写入 child 进程 1 或 child 进程 2,我将如何处理?

int p1[2];
int p2[2];
pid_t child_a, child_b;

 if(pipe(p1) == -1){
        printf("error in creating pipe\n");
        exit(-1);
    }

    if(pipe(p2) == -1){
        printf("error in creating pipe\n");
        exit(-1);
    }

child_a = fork();

if (child_a == 0) {
    /* Child A code */
} else {
    child_b = fork();

    if (child_b == 0) {
        /* Child B code */
    } else {
        /* Parent Code */
    }
}

您已经创建了两个管道,所以您的方向是正确的。您可以使用一个管道,比如 p1,将消息从父级发送到 child_a,并使用 p2 将消息发送到 child_b

您可以使用 dup2 切换标准输入文件描述符

int p1[2];
int p2[2];
pid_t child_a, child_b;

 if(pipe(p1) == -1){
        printf("error in creating pipe\n");
        exit(-1);
    }

    if(pipe(p2) == -1){
        printf("error in creating pipe\n");
        exit(-1);
    }

child_a = fork();

if (child_a == 0) {
    /* Child A code */
    // now can read from stdin to receive messages from parent process
    dup2(p1[0], STDIN_FILENO); 
    // don't forget to close file descriptors that are open in every process!
    close(p1[0]); close(p1[1]);
} else {
    child_b = fork();

    if (child_b == 0) {
        /* Child B code */
        dup2(p2[0], STDIN_FILENO); 
        close(p2[0]); close(p2[1]); 
    } else {
        /* Parent Code */
        // Write something to child A
        write(p1[1], some_text, num_bytes);
        // Write something to child B
        write(p2[1], some_other_text, num_other_bytes);
    }
}

请记住,write 需要一个 int 文件描述符、一个要写入的 void* 缓冲区——可以是 char* 和一个 int 写入文件描述符的字节数。

这是来自 POSIX API 的 write 文档:https://linux.die.net/man/2/write

这里是 dup2 的文档:https://linux.die.net/man/2/dup2