在Python中,可以使用os.pipe()
函數來創建管道。下面是一個簡單的示例:
import os
# 創建管道
r, w = os.pipe()
# 在子進程中向管道中寫入數據
pid = os.fork()
if pid == 0:
os.close(r)
os.write(w, b"Hello, pipe!")
os.close(w)
else:
os.close(w)
# 在父進程中從管道中讀取數據
data = os.read(r, 100)
print("Received data:", data.decode())
os.close(r)
在這個示例中,首先調用os.pipe()
函數創建了一個管道,然后使用os.fork()
函數創建了一個子進程,子進程中向管道中寫入了數據,父進程中從管道中讀取了數據。最后需要記得在使用完管道之后調用os.close()
函數關閉管道。