盒子
盒子

python 进程间管道通信

实现了两个 Linux 进程之间通过管道进行通讯的代码逻辑。分为 client.pyserver.py 运行时需要先运行 server 再运行 client

client.py

import os
import time

write_path = "pipe.in"
read_path = "pipe.out"

wf = os.open(write_path, os.O_SYNC | os.O_CREAT | os.O_RDWR)
rf = None
# rf = os.open(read_path, os.O_RDONLY)
for i in range(1, 11):
msg = "msg " + str(i)
msg = msg.encode()
len_send = os.write(wf, msg)
print ("sent msg: %s" % msg)

if rf is None:
rf = os.open(read_path, os.O_RDONLY)

s = os.read(rf, 1024)
if len(s) == 0:
break
print ("received msg: %s" % s)

time.sleep(1)

os.write(wf, 'exit'.encode())

os.close(rf)
os.close(wf)

server.py

import os, time

read_path = "pipe.in"
write_path = "pipe.out"

if os.path.exists(read_path):
os.remove(read_path)
if os.path.exists(write_path):
os.remove(write_path)

os.mkfifo(write_path)
os.mkfifo(read_path)

rf = os.open(read_path, os.O_RDONLY)
wf = os.open(write_path, os.O_SYNC | os.O_CREAT | os.O_RDWR)

while True:
s = os.read(rf, 1024)
print ("received msg: %s" % s)
if len(s) == 0:
time.sleep(1)
continue

if "exit".encode() in s:
break

os.write(wf, s)

os.close(rf)
os.close(wf)
支持一下
万一真的就有人扫了呢
  • 微信扫一扫
  • 支付宝扫一扫