我想从bash脚本启动一个后台Python作业,然后使用SIGINT优雅地终止它。这在shell中工作得很好,但是我似乎无法在脚本中让它工作。
loop.py:
#! /usr/bin/env python
if __name__ == "__main__":
try:
print 'starting loop'
while True:
pass
except KeyboardInterrupt:
print 'quitting loop'在shell中我可以中断它:
$ python loop.py &
[1] 15420
starting loop
$ kill -SIGINT 15420
quitting loop
[1]+ Done python loop.pykill.sh:
#! /bin/bash
python loop.py &
PID=$!
echo "sending SIGINT to process $PID"
kill -SIGINT $PID但是从一个脚本中我不能:
$ ./kill.sh
starting loop
sending SIGINT to process 15452
$ ps ax | grep loop.py | grep -v grep
15452 pts/3 R 0:08 python loop.py而且,如果它是从脚本启动的,我就不能再从shell中删除它:
$ kill -SIGINT 15452
$ ps ax | grep loop.py | grep -v grep
15452 pts/3 R 0:34 python loop.py我想我漏掉了一些bash任务控制的细节。
发布于 2017-12-14 04:51:57
尝试了@Steen的方法,但很遗憾,它显然不能坚持Mac。
另一种解决方案与上面的方案基本相同,但更一般,如果SIGINT被忽略,则只需重新安装默认处理程序:
def _ensure_sigint_handler():
# On Mac, even using `exec <cmd>` in `bash` still yields an ignored SIGINT.
sig = signal.getsignal(signal.SIGINT)
if signal.getsignal(signal.SIGINT) == signal.SIG_IGN:
signal.signal(signal.SIGINT, signal.default_int_handler)
# ...
_ensure_sigint_handler()https://stackoverflow.com/questions/974189
复制相似问题