1
votes

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

2

2 Answers

0
votes

If you were not able to exit the process which opens up a command window, you can try using os.exit(1) which will do the work for you.

0
votes

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.