Finding child pids

Bernhard Herzog herzog at intevation.de
Mon Mar 17 04:48:36 EST 2003


Tom Chance <tomchance at gmx.net> writes:

> ---
> # To open the pipe
> self.pipe = popen2.Popen3(command)
> 
> # To kill it (seperate section of the program)
> self.pid = self.pipe.pid + 1
> os.kill(self.pid, 9)
> os.waitpid(self.pipe.pid, os.WNOHANG)
> ---
> 
> The problem here is in the line where I have to add 1 to the pid of the
> child process. When I open the pipe, python opens the command with sh, and
> so the first child process is sh, and sh then makes the command its child
> process. SO... if I kill the pipe (sh), it just then leaves the command to
> detach and work on its own. So I have to increment the pid by one to kill
> the command instead. But this seems like a nasty hack to me.

And it doesn't always work for various reasons. E.g. if another process
is created in the time between starting the shell and the shell starting
its sub-process you'll likely to have to add 2 not 1. Of course there
isn't any guarantee that the child's PID is actually larger than the
shell's PID in the first place. At least on Linux the PIDs don't always
increase.
 
> How can I get the pid of the command, and not just sh?

Don't use a string. Use a list of strings with one string for each
argument. E.g. instead of

"mycommand arg1 arg2" use ["mycommand", "arg1", "arg2"]

This has the additional benefit that you don't have to worry about
quoting.

  Bernhard

-- 
Intevation GmbH                                 http://intevation.de/
Sketch                                 http://sketch.sourceforge.net/
MapIt!                                               http://mapit.de/




More information about the Python-list mailing list