在调试另一个question时,我发现如果Python是从带有&
的shell脚本启动的,那么SIGINT的信号处理设置会更改为忽略它
x.py
内容:
import signal
print(signal.getsignal(signal.SIGINT))
noproblem.sh
内容:
python3 x.py
problem.sh
内容:
python3 x.py &
直接运行x.py
时,直接使用&
或通过noproblem.sh
运行时,SIGINT的信号处理程序是默认的signal.default_int_handler
,它负责引发键盘中断:
07:14 ~ $ python3 x.py
<built-in function default_int_handler>
07:14 ~ $ python3 x.py &
[1] 126909
07:14 ~ $ <built-in function default_int_handler>
[1]+ Done python3 x.py
07:14 ~ $ bash noproblem.sh
<built-in function default_int_handler>
但是通过运行x.py
到problem.sh
,SIGINT被忽略:
07:14 ~ $ bash problem.sh
07:14 ~ $ Handlers.SIG_IGN
我找不到任何文档来解释为什么会发生这种情况。{a2}没有提到这种行为。这是故意的,还是错误
经过进一步的挖掘,我终于找到了原因
首先,如果Python从其父进程继承了操作系统级别的SIG_IGN for SIGINT设置,则不会安装默认的SIGINT处理程序。它仅在继承SIG_DFL设置时安装该处理程序。我们可以在
signal
模块的source code中看到这一点:其次,shell脚本在默认情况下在禁用作业控制的情况下运行,而在禁用作业控制时以
&
启动的进程将继承SIGINT和SIGQUIT的SIG_-IGN设置。引用POSIX:我在shell脚本中找不到一个明确的标准引用,说默认情况下禁用了作业控制,只有quotes说默认情况下为交互式shell启用了作业控制(模糊地暗示非交互式shell的相反设置):
相关问题 更多 >
编程相关推荐