簡體   English   中英

使用一個 Pipe (Linux) 在 C 中創建雙向 Pipe 用於讀取和寫入

[英]Creating Bidirectional Pipe in C For Both Reading and Writing Using One Pipe (Linux)

是否可以使用一個 pipe 在進程之間進行讀寫? 我的偽代碼很像下面。 我試過了,但它給了我一個錯誤,說“錯誤的文件描述符”。

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

提前非常感謝。

當您關閉文件描述符時,您將無法再使用它。
pipe 是單向的; 在許多應用程序中,您只需在兩個進程之間決定哪一個是讀取器,哪一個是寫入器。
但是通過特定的同步,您可以按照示例中的建議交換這兩個角色(請參閱下面的編輯)。

如果您需要雙向 stream,您可以使用socketpair(PF_LOCAL, SOCK_STREAM, 0, fd)


編輯,關於關閉不要太早

當您確定您的流程不再需要它時,只需關閉 pipe 的一端即可。

只是不要指望在同步信號之前檢測到文件結束,因為 pipe 的另一端還沒有關閉。

這個例子可能會有所幫助。

#!/usr/bin/env python

import sys
import os
import signal

fd=os.pipe()
p=os.fork()
if p==0:
  signal.signal(signal.SIGUSR1, lambda signum, frame: 0)
  os.write(fd[1], b'A')
  os.close(fd[1]) # I will never write again to this pipe
  signal.pause() # wait for the signal before trying to read
  b=os.read(fd[0], 1)
  os.close(fd[0]) # I will never read again from this pipe
  sys.stdout.write('child got <%s>\n'%b)
else:
  a=os.read(fd[0], 1)
  os.close(fd[0]) # I will never read again from this pipe
  sys.stdout.write('parent got <%s>\n'%a)
  os.kill(p, signal.SIGUSR1) # now the child is allowed to read
  os.write(fd[1], b'B')
  os.close(fd[1]) # I will never write again to this pipe
  os.wait()

是否可以使用一個 pipe 在進程之間進行讀寫?

從技術上講,是的,兩個進程可以使用單個 pipe 進行雙向通信。 pipe 本身沒有特殊要求來啟用此功能,但每個進程必須讓每個 pipe 端打開,只要他們想使用該端(與您的偽代碼相反)。 不過要明確一點:管道有一個寫端和一個讀端。 所有對 pipe 的寫入都必須 go 到寫入端,並且所有讀取都必須在讀取端執行,但多個進程可以使用每一端。

但是以這種方式使實際的雙向通信正常工作是非常棘手的,因為寫入 pipe 的任何數據都可以被任何打開讀取端的進程讀取,包括寫入它的進程(盡管只有一個會實際讀取每個字節),並且因為只要任何進程打開寫端,就沒有進程會在 pipe 的讀端觀察到文件結束信號。 因此,要雙向使用單個 pipe,您需要一些額外的 IPC 機制在通信進程之間進行調解,以確保每個進程都接收完整的消息,消息不會混合,並且如果適用,每個進程只接收定向的消息給它。

為每對通信進程設置兩個管道要容易得多,每個方向一個。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM