A way to discover PIDs of child processes?

S

schreckmail

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!
 
D

Donn Cave

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

It doesn't always have to be that way, depending on the
nature of the command. If it's the last thing the shell
has to do, then it can be exec'ed without a fork, which
leaves the gdb image running in the immediate child process.

Some shells do that automatically. In any case, a Bourne
shell "exec" statement will do it, like "exec /.../gdb",
with whatever redirections etc.

Donn Cave, (e-mail address removed)
 
S

schreckmail

Donn,

Your suggestion worked perfectly. Thank you for showing me the forest
from the trees :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top