使用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