Server进程创建管道:
import os
# 定义管道名称
pipe_file = "/tmp/notify.pipe"
# 如果之前就存在了,删掉它
if os.path.exists(pipe_file):
os.remove(pipe_file)
# 定义管道
os.mkfifo(pipe_file)
# 打开管道
pipe = os.open(pipe_file, os.O_SYNC | os.O_CREAT | os.O_RDWR)
此时,只需要使用语句
pipe.write(b"message")
即可向管道内写入数据。
此时,cat一下这个管道,你会收到一条message。
如果希望用python读取管道数据,使用下面的代码:
pipe_file = "/tmp/notify.pipe"
# RDONLY表示只读。如果双向通讯,可以去掉
pipe = os.open(pipe_file, os.O_RDONLY | os.O_NONBLOCK)
# 读取1024个字节
os.read(pipe, 1024)