简体   繁体   中英

Sending a string between two processes using named pipes

I am trying to send a string, "Hi" from Child1 to Child3 which are two sibling processes. The code runs, however i do not receive the input from Child1 in Child3.

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <sys/stat.h>

#define MSGSIZE 1024

int main (int argc, char *argv[]){

    int  fd;
    char * myfifo = "/desktop/myfifo";
    char  l[MSGSIZE];
    pid_t child1, child3;
    mkfifo(myfifo, 0666);
    child1 = fork();

if (child1 == 0) {

    printf("I am Child 1: %d \n", (int)getpid());
            fd = open(myfifo, O_WRONLY);
            write(fd,  "Hi", MSGSIZE);
            close(fd);
    } 

else {

    if (child1 > 0 ) {
       printf("I am parent: %d \n", (int)getpid());

        wait(0);
    }

    child3 = fork();

    if (child3 == 0) {
        printf("I am Child 3: %d \n", (int)getpid());

        fd = open(myfifo, O_RDONLY);
        read(fd, l, MSGSIZE);
        printf("Received: %s \n", l); 

        close(fd);
    } 
}
    wait(0);
    unlink(myfifo);
    return 0;
}

Hope someone can point me in the right direction.

Unless you're doing non-blocking IO, opening one end of a FIFO will block until the other is also opened. So child1 blocks in its open(2) call until child3 opens their end of the pipe. However, you're also calling wait(2) in the parent process before you fork off child3 .

So you have a deadlock: Parent is waiting on child1 to fork child3 , but child1 is waiting for child3 to open the other end of the pipe.

You can fix this in at least two ways. First, just put the wait(2) call after you fork the second child process. The other way is to create a pipe(2) in the parent process, and let the children inherit these descriptors and pass data to each other that way.

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