进程间通信、操作系统、管道

Posted

技术标签:

【中文标题】进程间通信、操作系统、管道【英文标题】:Inter-Process Communication, Operating Systems, Pipes 【发布时间】:2017-02-11 18:26:55 【问题描述】:

我在一本书中读到,为了在两个进程之间使用管道进行进程间通信,最好使用两个管道,一个供孩子在其中写入,而供父亲从中读取另一个做相反的沟通。为什么这是一种更好的方法?我们不能只使用一个管道,以便父母和孩子都可以读取和写入吗?

【问题讨论】:

【参考方案1】:

您需要一种方法来同步进程之间的通信,否则进程将一次又一次地读取/写入它写入/读取的内容。例如如果您使用一根管道:

//parent
while(1)

    write(p1);
    //need a logic to wait so as to read what child wrote back and also so
    // that we may not end up reading back what we wrote.
    read(p1);

//child
while(1)

    read(p1);
    //need a logic to wait so as to read what child wrote back and also so
    // that we may not end up reading back what we wrote.
    write(p1);

找到一个万无一失的逻辑来同步或使用两个管道。我是说傻瓜式等待,因为像sleep()signals 这样的简单技术很容易受到操作系统人员在其工作中概述的调度问题的影响。

管道本身就是阻塞结构,所以要依赖它们来同步。

//parent
while(1)

    write(p1);
    //pipe blocks until till child writes something in pipe
    read(p2);

//child
while(1)

    //pipe waits for parent to write.
    read(p1);
    //parent is waiting to read.
    write(p2);

【讨论】:

以上是关于进程间通信、操作系统、管道的主要内容,如果未能解决你的问题,请参考以下文章

进程间通信( 管道 )

多进程编程之进程间通信-管道和消息队列

进程间通信

进程间通信、操作系统、管道

进程间通信的方法

Linux——进程间通信——管道与共享内存