我有一个 python 脚本,在调用时将一些数据写入管道:
def send_to_pipe(s):
send = '/var/tmp/mypipe.pipe'
sp = open(send, 'w')
sp.write(json.dumps(s))
sp.close()
if __name__ == "__main__":
name = sys.argv[1]
command = sys.argv[2]
s = {"name":name, "command":command}
send_to_pipe(s)
然后我有这个文件,可以无限期地保持管道打开并在每次调用上述脚本时读取数据:
def watch_pipe():
receive = '/var/tmp/mypipe.pipe'
os.mkfifo(receive)
rp = os.open(receive, os.O_RDWR | os.O_NONBLOCK)
p = select.poll()
p.register(rp, select.POLLIN)
while True:
try:
if p.poll()[0][1] == select.POLLIN:
data = os.read(rp,512)
# Do some stuff with the data
except:
os.close(rp)
os.unlink(receive)
if __name__ == "__main__":
t = Thread(target=watch_pipe)
t.start()
# Do some other stuff that goes on indefinitely
当我使用线程时,这段代码工作得很好。管道保持打开状态,第一个文件写入管道,然后事情就完成了。问题是当我想关闭程序时我无法停止线程。所以我从线程切换到进程:
p = Process(target=watch_pipe)
p.start()
但是使用进程而不是线程,当我运行编写器脚本时,open(send, 'w')
会删除管道,就好像它是我想要覆盖的文件一样。为什么是这样?在这两种情况下,文件的权限和所有权是相同的,并且编写器脚本不会更改。唯一改变的是用类似的 Process 对象替换 Thread 对象。
编辑:将打开更改为使用“a”而不是“w”后,使用进程时管道仍然会消失。
最佳答案
你为什么要为难自己?您在您所说的在线程中使用的例程中将 FIFO 作为 O_RDWR 打开。如果您想关闭该线程,只需将任何其他正在关闭该线程的线程写入“停止”消息到 FIFO 即可。线程读取消息,自行关闭,世界又恢复正常了。没有大惊小怪,没有困惑,不需要单独的过程。
关于python - python线程和进程之间的管道有不同的行为吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21613906/