使用管道在父程序和子程序之間進行通訊的 Python 程式。
使用 fork 是建立子程序的最簡單方法。fork() 是 os 標準 Python 函式庫的一部分。
在這裡,我們透過使用 pipe() 來解決此任務。對於將資訊從一個程序傳遞到另一個程序,我們使用 pipe()。對於雙向通訊,可以使用兩根管道,每根管道一根,因為 pipe() 是單向的。
演算法
Step 1: file descriptors r, w for reading and writing. Step 2: Create a process using the fork. Step 3: if process id is 0 then create a child process. Step 4: else create parent process.
示例程式碼
import os def parentchild(cwrites): r, w = os.pipe() pid = os.fork() if pid: os.close(w) r = os.fdopen(r) print ("Parent is reading") str = r.read() print( "Parent reads =", str) else: os.close(r) w = os.fdopen (w, 'w') print ("Child is writing") w.write(cwrites) print("Child writes = ",cwrites) w.close() # Driver code cwrites = "Python Program" parentchild(cwrites)
輸出
Child is writing Child writes = Python Program Parent is reading Parent reads = Python Program
廣告