A way to discover PIDs of child processes?

schreckmail at yahoo.com schreckmail at yahoo.com
Fri Feb 17 12:53:43 EST 2006


Hi all!

I'm launching a subprocess using the following code, and I'd like to
kill off all associated subprocesses after a given timeout:

myproc = popen2.Popen3(command)

Now, because the command is executed in the shell, I end up with the
following process tree:

      PID    PPID    PGID     WINPID  TTY  UID    STIME COMMAND
     2332    3156    2332       3412  con 1012 15:34:11
/usr/bin/python2.4
     3068    2332    2332       2268  con 1012 15:34:11 /usr/bin/sh
     1584    3068    2332       2620  con 1012 15:34:12
/cygdrive/c/GNATPRO/5.01
a/bin/powerpc-elf-gdb


Here are the two options I've come up with:
1) I can kill 3068 using os.kill(myproc.pid, signal.SIGKILL), but that
keeps 1584 running and therefore doesn't do the trick.

2) I can kill the group of processes (2332) using
os.killpg(os.getpgid(myproc.id), signal.SIGKILL), but that terminates
Python as well, and I'd rather continue on my merry way in Python...

Here's my code:

myproc = popen2.Popen3(command)

second_count = 0
while myproc.poll() == -1:
    time.sleep(1) # wait a sec
    second_count = second_count + 1
    if second_count == 30:
        ##use commented code to kill group
        ##pgid = os.getpgid(myproc.pid)
        ##os.killpg(pgid, signal.SIGKILL)
        os.kill(myproc.pid, signal.SIGKILL)

One solution I've considered is using the Popen class to launch the
subprocess with shell=False.  This would eliminate the shell process so
I'd only have one process to kill.... but I've got some I/O redirection
in my command string that I'd like to pass along to the shell.  I think
I need the shell there for other reasons as well.  Any idea how I can
know if a given process has children and find out what their PIDs are?

Any suggestions are greatly appreciated!




More information about the Python-list mailing list