pausing or killing a process

Carsten Gaebler news at snakefarm.org
Tue Feb 4 17:49:37 EST 2003


David Martens wrote:
> Is there a reasonable way of pausing a process
> within Python?

Send it a SIGSTOP:

os.kill(pid, 19)

It will pause until it gets a SIGCONT:

os.kill(pid, 18)


> Additionally, a process can be killed by doing a 
> os.system("kill -9 %i" % pid) but that falls short
> of elegant.  Can it be done better?

os.kill(pid, 9)

But you should send a SIGTERM first to give the process a chance to exit 
cleanly. Then perhaps wait some time and finally really kill it:

# send SIGTERM
os.kill(pid, 15)
# give time to finish
time.sleep(2)
# kill it (beware of exceptions!)
os.kill(pid, 9)

Instead of a dumb sleep() you could wait until the process really 
finishes. If the process has been forked within the program, loop over 
os.waitpid(pid, os.WNOHANG) as long as you feel appropriate. It will 
return the pid once the child exits. If the process is not a child of 
your program, but the owners are the same, check by sending signal 0 
(os.kill(pid, 0)). This will raise an exception if the child is not there.


cg.





More information about the Python-list mailing list