首页 > 解决方案 > Creating Bidirectional Pipe in C For Both Reading and Writing Using One Pipe (Linux)

问题描述

Is it possible to use one pipe for both writing and reading between processes? My pseudocode is pretty much like below. I tried but it gave me an error said "bad file descriptor".

create fd[2]
create pipe(fd)

parent:
     close fd[0]
     write something to fd[1]
     close fd[1]
     // wait for child's signal
     close fd[1]
     read the response fd[0]
     close fd[0]

child:
     close fd[1]
     read the pipe fd[0]
     close fd[0]

    // write an answer to the parent via the existing pipe
    // no need to close fd[0], since it's already closed
     write the answer fd[1]
     close fd[1]
     signal to the parent

Thanks a lot in advance.

标签: cprocesspipeforkipc

解决方案


是否可以使用一个管道在进程之间进行写入和读取?

从技术上讲,是的,两个进程可以使用单个管道进行双向通信。管道本身没有特殊要求来启用此功能,但每个进程必须让每个管道端打开,只要他们想使用该端(与您的伪代码相反)。不过要明确一点:管道有一个写端和一个读端。对管道的所有写入都必须到写入端,并且所有读取都必须在读取端执行,但多个进程可以使用每一端。

但是以这种方式使实际的双向通信正常工作是非常棘手的,因为任何写入管道的数据都可以被任何打开读取端的进程读取,包括写入它的进程(尽管实际上只有一个进程会读取每个数据) byte),并且因为只要任何进程打开了写端,就没有进程会在管道的读端观察到文件结束信号。因此,要双向使用单个管道,您需要一些额外的 IPC 机制在通信进程之间进行调解,以确保每个进程都收到完整的消息,消息不会混合在一起,并且如果适用,每个进程只接收定向的消息给它。

为每对通信进程设置两个管道要容易得多,每个方向一个。


推荐阅读