Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

How to get a PID of a child process from a process openden with Popen()

690 views
Skip to first unread message

P.S.

unread,
Apr 8, 2011, 6:40:10 AM4/8/11
to
Hello,

I am starting a GUI-application as another user with kdesu in my python
script:

import shlex, subprocess

p = subprocess.Popen(shlex.split("kdesu -u test program"))

How can I aquire the PID of the program which kdesu starts?
p.pid just returns the PID of kdesu, but I need the PID of the
child process from kdesu.

My System: openSUSE 11.4 64-Bit, Python 2.7.

Regards
Pedro Santos

Miki Tebeka

unread,
Apr 8, 2011, 10:43:41 AM4/8/11
to
> p = subprocess.Popen(shlex.split("kdesu -u test program"))
>
> How can I aquire the PID of the program which kdesu starts?
You can run "ps --ppid <p.pid>" and get the line containing test program.
The first field there should be the child process id.

HTH
--
Miki Tebeka <miki....@gmail.com>
http://pythonwise.blogspot.com

Nobody

unread,
Apr 8, 2011, 3:28:43 PM4/8/11
to
On Fri, 08 Apr 2011 07:43:41 -0700, Miki Tebeka wrote:

>> p = subprocess.Popen(shlex.split("kdesu -u test program"))
>>
>> How can I aquire the PID of the program which kdesu starts?
>
> You can run "ps --ppid <p.pid>" and get the line containing test program.
> The first field there should be the child process id.

This will fail if the kdesu process has terminated at that point (the
documentation doesn't say whether it waits for the child to terminate).
Once a process' parent has terminated, it's PPID will become 1 (i.e. it
will be "adopted" by the init process).

There isn't a robust solution to the OP's problem. It's typically
impossible to determine whether one process is an ancestor of another if
any of the intermediate processes have terminated.

Chris Angelico

unread,
Apr 8, 2011, 6:35:23 PM4/8/11
to pytho...@python.org
On Sat, Apr 9, 2011 at 5:28 AM, Nobody <nob...@nowhere.com> wrote:
> There isn't a robust solution to the OP's problem. It's typically
> impossible to determine whether one process is an ancestor of another if
> any of the intermediate processes have terminated.

Upstart and gdb can both detect forks and follow the child. But I
think that's getting into some serious esoteria that's unlikely to be
of much practical use here.

Chris Angelico

0 new messages