On Thu, Dec 10, 2009 at 01:53:51PM -0700, Bryan Murdock wrote:
> I keep hearing a voice saying, "UR doing it r0ng!" I have a python
> program that is running shell commands. I'm using the subprocess
> library. Some of the shell commands take a long time. When I kill
> the python process (SIGTERM), the subprocess keeps on going. I want
> it to die too. So I registered a SIGTERM handler to manually
> terminate the subprocess, but I still get some ugliness. Here's a
> boiled down example of what I'm attempting:
It sounds like you're approach is basically working. I'll give you one
minor improvement and then suggest another way to look at the problem.
1) Here's a minor change to your approach:
> proc = None
killed = False
> def cleanup(signum, frame):
global killed
> print "cleaning up"
> if proc:
> proc.terminate()
killed = True
>
> command = 'while [ 1 ]; do echo "still running"; sleep 1; done'
> print "running command: " + command
>
> signal(SIGTERM, cleanup)
> proc = subprocess.Popen(command, shell=True)
try:
proc.communicate()
except OSError:
if not killed:
raise
This gets rid of your ugly OSError.
2) Alternatively, you can create a new process group with setpgid() (and
you might have to create a new session, too, with setsid()--I'd have to
think about this a little bit more). If your Python script is a process
group leader, then all other processes in the group should be killed if
your script (the process group leader) exits.
--
Andrew McNabb
http://www.mcnabbs.org/andrew/
PGP Fingerprint: 8A17 B57C 6879 1863 DE55 8012 AB4D 6098 8826 6868
--------------------
BYU Unix Users Group
http://uug.byu.edu/
The opinions expressed in this message are the responsibility of their
author. They are not endorsed by BYU, the BYU CS Department or BYU-UUG.
___________________________________________________________________
List Info (unsubscribe here): http://uug.byu.edu/mailman/listinfo/uug-list