TL;DR:为什么关闭收到 SIGPIPE 异常的 fifo 文件(命名管道)会产生另一个 SIGPIPE 异常?
我的 python 脚本正在通过 FIFO 文件将字节写入另一个进程,该进程是我的 python 进程的子进程。(有一些限制,我必须使用命名管道。)
我必须考虑到子进程可能会提前终止的事实。如果发生这种情况,我的 python 脚本必须获取死子进程并重新启动它。
要查看子进程是否死亡,我只是先尝试写入 FIFO,如果我得到一个 SIGPIPE 异常(实际上是 IOError 表示管道损坏),我知道是时候重新启动我的子进程了。
最小的例子如下:
#!/usr/bin/env python3
import os
import signal
import subprocess
# The FIFO file.
os.mkfifo('tmp.fifo')
# A subprocess to simply discard any input from the FIFO.
FNULL = open(os.devnull, 'w')
proc = subprocess.Popen(['/bin/cat', 'tmp.fifo'], stdout=FNULL, stderr=FNULL)
print('pid = %d' % proc.pid)
# Open the FIFO, and MUST BE BINARY MODE.
fifo = open('tmp.fifo', 'wb')
# Endlessly write to the FIFO.
while True:
# Try to write to the FIFO, restart the subprocess on demand, until succeeded.
while True:
try:
# Optimistically write to the FIFO.
fifo.write(b'hello')
except IOError as e:
# The subprocess died. Close the FIFO and reap the subprocess.
fifo.close()
os.kill(proc.pid, signal.SIGKILL)
proc.wait()
# Start the subprocess again.
proc = subprocess.Popen(['/bin/cat', 'tmp.fifo'], stdout=FNULL, stderr=FNULL)
print('pid = %d' % proc.pid)
fifo = open('tmp.fifo', 'wb')
else:
# The write goes on well.
break
要重现结果,请运行该脚本并手动终止子进程kill -9 <pid>
。回溯会告诉你
Traceback (most recent call last):
File "./test.py", line 24, in <module>
fifo.write(b'hello')
BrokenPipeError: [Errno 32] Broken pipe
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "./test.py", line 27, in <module>
fifo.close()
BrokenPipeError: [Errno 32] Broken pipe
那么为什么关闭 FIFO 文件会产生另一个 SIGPIPE 异常呢?
我在以下平台上进行了测试,结果是一样的。
Python 3.7.6 @ Darwin Kernel Version 19.3.0 (MacOS 10.15.3)
Python 3.6.8 @ Linux 4.18.0-147.3.1.el8_1.x86_64 (Centos 8)