编制一段程序,实现进程的管道通信。使用系统调用pipe()建立一条管道线。两个子进程p1和p2分别向管道各写一句话: child 1 is sending a message! child 2 is sending a message!
时间: 2024-12-12 09:17:56 浏览: 88
在Linux环境中,你可以使用`fork()`、`pipe()`和`write()`系统调用来创建一个简单的管道通信示例。下面是一个简化的Python脚本示例,它展示了如何在两个子进程中通过管道进行通信:
```python
import os
# 创建一个管道
def create_pipe():
parent_rfd, child_wfd = os.pipe()
return parent_rfd, child_wfd
# 子进程p1 写入消息
def child1(parent_rfd):
msg = "child 1 is sending a message!"
try:
os.write(parent_rfd, msg.encode())
print(f"Child 1 wrote to pipe: {msg}")
except BrokenPipeError:
print("Parent process closed the pipe.")
finally:
os.close(parent_rfd)
# 子进程p2 写入消息
def child2(child_wfd):
msg = "child 2 is sending a message!"
try:
os.close(child_wfd)
os.write(1, msg.encode()) # 使用标准输出代替关闭后的写入
print(f"Child 2 wrote to pipe (using stdout): {msg}")
except IOError:
print("Write failed, probably because the pipe was already closed.")
if __name__ == "__main__":
# 创建管道
parent_rfd, child_wfd = create_pipe()
# 创建并启动子进程p1
p1_pid = os.fork()
if p1_pid == 0: # 子进程
child1(parent_rfd)
else: # 父进程
os.waitpid(p1_pid, 0) # 等待子进程结束
# 创建并启动子进程p2
p2_pid = os.fork()
if p2_pid == 0: # 子进程
child2(child_wfd)
else: # 父进程
os.waitpid(p2_pid, 0) # 等待子进程结束
# 父进程关闭自己的管道读端,模拟接收完成
os.close(parent_rfd)
```
运行这个脚本,你会看到两个子进程分别向管道发送了它们的消息。注意,因为父进程在收到第一个孩子的消息后就关闭了读端,所以第二个孩子会遇到`BrokenPipeError`。
阅读全文
相关推荐















