我有一个python脚本,我想通过使用命令行发送"SIGINT"信号来停止它:
kill -2 <PID>
该脚本生成一个子进程,然后进入无限循环,尝试从套接字接收数据。我已经安装了信号处理程序,但看起来我的程序没有捕捉到信号。这是我的代码:
import signal
import multiprocessing
def newBreakHandler(signum, frame):
global progBreak
progBreak = True
def runMain():
client = multiprocessing.Client(<address>)
# ......
# Insert break handler
signal.signal(signal.SIGINT, newBreakHandler)
while not progBreak:
try:
# Some other stuff...
# ...
childProc = multiprocessing.Process(target=childProcName)
childProc.start()
# Main loop
while not progBreak:
command = client.recv_bytes()
except:
pass
print "Exiting..."
问题是每当我发送:
kill -2 <PID>
我从未看到打印的"退出"文本,并且PID没有被杀死。我认为这是因为内部"while"循环正忙于等待来自客户端的新数据,但如果客户端没有发送新数据。
有没有办法解决问题?
蒂亚!!
看起来您的内部循环正在阻止progBreak
检查,这段代码对我有用:
import signal
progBreak = False
def newBreakHandler(signum, frame):
global progBreak
progBreak = True
def runMain():
global progBreak
signal.signal(signal.SIGINT, newBreakHandler)
while not progBreak:
while not progBreak and client.poll():
command = client.recv_bytes()
print "Exiting..."
runMain()