[英]Why kill command can not terminate nohup python thread
代碼:
res = Subprocess.Popen(cmd,executable="/bin/bash", shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
while not res.poll():
do something....
我運行python代碼,如:nohup python my_script.py&
然后我想終止sctipt:
kill pid_of_the_script
但它不起作用(所以由Subprocess.Popen創建的cmd procss仍將存在)我必須使用:
kill -9 pid_of_the_script
為什么kill命令在這里不起作用?
由於kill -9也沒有殺死cmd進程,當我捕獲一個SIGTERM信號時(這就是問題,就像我發送一個kill命令一樣,腳本無法捕獲這個信號,我確實將SIGTERM信號注冊到一個信號處理程序),處理程序首先殺死cmd進程,然后使用kill -9來殺死腳本本身(基於pid)。
更新:也許thread.join()方法導致這個。 在主線程中調用join,主線程似乎無法處理信號......
如果您無法退出打開命令窗口的進程,可以嘗試使用os.exit(1)
來為您完成工作。
我使用以下代碼作為解決方法:
thread1.start() # process in thread1 is an infinite task
while some_condition: # use a infinite loop here
time.sleep(10)
thread1.join() # join after the loop, so before calling join, the
# main thread can response to the signals
添加信號處理程序
def signal_handler(signum, frame):
print "receive sig %d " % signum
# kill the process started by thread1
...
# modify condition value here, so the above infinite loop can exit now
...
將信號處理程序注冊到SIGTERM
signal.signal(signal.SIGTERM, signal_handler)
現在我可以使用ctrl + C或kill來終止主進程及其子進程。
由於thread1中的任務是無限的,似乎將其設置為守護程序線程也可以工作,因此主線程無需調用join(),只需睡眠即可。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.