简体   繁体   中英

Why kill command can not terminate nohup python thread

Code :

res = Subprocess.Popen(cmd,executable="/bin/bash", shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE)

while not res.poll():
     do something....

I run the python code like: nohup python my_script.py &

And then i want to terminate the sctipt:

kill pid_of_the_script

But it does not work(so the cmd procss created by Subprocess.Popen will be still there) i must use:

kill -9 pid_of_the_script

why the kill command not work here?

As the kill -9 does not kill the cmd process neither, when i capture a SIGTERM signal(this is the problem, as when i send a kill command, the script can not capture this signal, i do register the SIGTERM signal to a signal handler), the handler first kills the cmd process and then use kill -9 to kill the script itself(based on the pid).

updated: maybe the thread.join() method causes this. where call join in the main thread, the main thread seems to can not handler signals...

如果您无法退出打开命令窗口的进程,可以尝试使用os.exit(1)来为您完成工作。

i used the following code as a workaround:

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            

add signal handler:

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
    ...

register the signal handler to SIGTERM

signal.signal(signal.SIGTERM, signal_handler)

Now i can use ctrl+C or kill to terminate the main process and its child processes.

As the task in thread1 is infinite, it seems that set it as a daemon thread can also work, so the main thread has no need to call join(), just sleep will be OK.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM