使用管道在父进程和子进程之间进行通信的 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP