简体   繁体   中英

When a parent has written data into a pipe shared with a forked child and both are reading data, how to prevent parent from reading it before child?

I have a C language code implementing pipes for parent and child communication. I constantly need to read and write from both parent and child. A smaller version of code is as follows:

int main(){
    int cpid, var;
    int fds[2];

    pipe(fds);

    if((cpid=fork())==0){
        read(fds[0], &var, sizeof(int));
        printf("Recieved in child - %d\n",var);

        var = 3;
        write(fds[1], &var, sizeof(int));
        printf("Writing from child - %d\n",var);

        exit(0);
    }

    var = 5;
    write(fds[1], &var, sizeof(int));
    printf("Writing from parent - %d\n",var);

    // I need something here to execute following read only after child writes

    read(fds[0], &var, sizeof(int));
    printf("Recieved in parent - %d\n",var);

    waitpid(cpid,NULL,0);
    return 0;
}

But I am facing problem that the read in parent process is getting executed just after write from parent. I need to prevent this from happening. Is there any way we can stop read in parent until child has written in above code? Any algorithms or suggestions are welcome.

PS: I have tried using signals like SUGUSR1 and pausing the parent until child sends the signal but as signals are not queued the concept of signals in this case fails for multiple child parent pipe communication.

According to comments from @JonathanLeffler and @EugeneSh. single pipe is not suited for bidirectional communication. So the above code can be modified to use one pipe for parent-child and one pipe for child-parent communication as follows:

int main(){
    int cpid, var;
    int p2c[2], c2p[2];

    pipe(p2c);
    pipe(c2p);

    if((cpid=fork())==0){
        read(p2c[0], &var, sizeof(int));
        printf("Recieved in child - %d\n",var);

        var = 3;
        write(c2p[1], &var, sizeof(int));
        printf("Writing from child - %d\n",var);

        exit(0);
    }

    var = 5;
    write(p2c[1], &var, sizeof(int));
    printf("Writing from parent - %d\n",var);

    read(c2p[0], &var, sizeof(int));
    printf("Recieved in parent - %d\n",var);

    waitpid(cpid,NULL,0);
    return 0;
}

This would apply to multiple child-parent logic also.

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