编程使用匿名管道从父进程向子进程发送你自己的学号,子进程收到后用另一个管道向父进程发回你自己的姓名;对收到的数据要显示到屏幕
时间: 2023-05-28 13:04:35 浏览: 55
下面是一个Python示例代码:
父进程:
```python
import os
# 创建匿名管道
r, w = os.pipe()
# 创建子进程
pid = os.fork()
if pid == 0:
# 子进程
# 关闭写端
os.close(w)
# 从管道中读取学号
num = os.read(r, 100)
# 关闭读端
os.close(r)
# 向父进程发送姓名
w2, r2 = os.pipe()
os.write(w2, b"Your Name")
os.close(w2)
# 显示收到的学号和发送的姓名
print("Received student number:", num.decode())
print("Sent name: Your Name")
else:
# 父进程
# 关闭读端
os.close(r)
# 向子进程发送学号
os.write(w, b"2021000000")
os.close(w)
# 从管道中读取子进程发送的姓名
r2, w2 = os.pipe()
name = os.read(r2, 100)
os.close(r2)
# 显示收到的姓名
print("Received name:", name.decode())
```
子进程收到的输出:
```
Received student number: 2021000000
Sent name: Your Name
```
父进程收到的输出:
```
Received name: Your Name
```