简体   繁体   中英

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

Below I have code of a parent process creating two child processes that belong to it. Now, I know I can make it so that the parent can write to a child process and the child process can read from it using read() and write().

My question is, is it possible for the parent to choose in this code below which child to write to? For example I asked the user of the program if he wanted to write to child process 1 or child process 2 with their own supplied message, how would I go about that?

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 */
    }
}

You've already created two pipes, so you're on the right track. You can use one pipe, say p1 , to send messages from the parent to child_a , and use p2 to send messages to child_b .

You can use dup2 to switch the stdin file descriptor for a

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

Keep in mind that write takes an int file descriptor, a void* buffer to write -- which can be a char* , and an int number of bytes to write to the file descriptor.

Here's the write documentation from the POSIX API: https://linux.die.net/man/2/write

And here's the documentation for dup2 : https://linux.die.net/man/2/dup2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM