简体   繁体   English

当父母将数据写入与分叉子项共享的管道并且两者都正在读取数据时,如何防止父母在孩子之前阅读它?

[英]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. 我有一个C语言代码实现父子通信的管道。 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. PS:我尝试使用像SUGUSR1这样的信号并暂停父节点直到子节点发送信号,但由于信号没有排队,因此在这种情况下信号的概念因多个子父管道通信而失败。

According to comments from @JonathanLeffler and @EugeneSh. 根据@JonathanLeffler和@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. 这也适用于多个子父逻辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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