5

I am trying to get the ppid of the process that I want.

I used following code to get the pid

proc=subprocess.Popen('ps -ae | grep ruby', shell=True, stdout=subprocess.PIPE, )
output=proc.communicate()[0]
str = output.split()

Now in the str[0], I have the pid of the process say ruby, I want to get the parent process ID ppid and child process ID of the same process.

I need this solution to be run on Solaris as well as Red Hat Enterprise Linux 6.0

Is there any way to get that like getppid() and getchildid()? Or do I need to do it by grep command again and splitting?

ajay_t
  • 2,347
  • 7
  • 37
  • 62

3 Answers3

8

Using this code is a bad idea. Your code will not work on solaris. You can use 'psutil' library, that way you can keep your code independent of os. https://github.com/giampaolo/psutil

p = psutil.Process(7055)
parent_pid = p.ppid()
Giampaolo Rodolà
  • 12,488
  • 6
  • 68
  • 60
Arovit
  • 3,579
  • 5
  • 20
  • 24
1

I presume there's nothing wrong with os.getppid() .

Shrug.

http://docs.python.org/3/library/os.html#process-parameters

dstromberg
  • 6,954
  • 1
  • 26
  • 27
0

The answer depends on your system's ps command. On Linux, ps will include the PPID for each process with the -l flag (among others), so ps -ale | grep ruby will include the ruby process id in str[3] and ruby's PPID in str[4].

Tim Pierce
  • 5,514
  • 1
  • 15
  • 31