4

How do you get the parent process id of a process that is not the current process in Ruby?

I've checked Ruby's Process module, but it only seems to provide a means to access the PPID of the current process.

I also checked google for anything on the subject, but the first two pages seemed to only contain links regarding how to use the aforementioned Process module.

I was hoping to do this without having to rely too much on the underlying OS, but whatever works.

tshepang
  • 12,111
  • 21
  • 91
  • 136
Alexej Magura
  • 4,833
  • 3
  • 26
  • 40
  • Is this an application that you are writing, or an application that you are running? Either way, this would need to manage process id's via some kind of housekeeping mechanism. Perhaps storing it in a class variable. Outside of Ruby, in your operating system, there should be a way to see the heirarchy. For Unix and Unix like systems, this would be using `ps`. – vgoff Jul 17 '13 at 03:22
  • 2
    @vgoff, writing, and I was trying to avoid using `ps`, but I neglected explicitly saying that. – Alexej Magura Jul 17 '13 at 03:23
  • Yep. Also forgot to give some code that shows how you are generating processes, and shows what you are trying to do that isn't working. – vgoff Jul 17 '13 at 03:49
  • Actually, no because I haven't written it yet. The question is, 'How do I do this, so that I *can* write it'. I could easily write this using the underlying OS, but I was hoping to implement it in pure Ruby. – Alexej Magura Jul 17 '13 at 04:17
  • 1
    You will want to do some research on working with Unix processes with Ruby. Perhaps read a blog post by Jesse Storimer that covers things like process_id, etc. http://www.jstorimer.com/blogs/workingwithcode/7766093-daemon-processes-in-ruby – vgoff Jul 17 '13 at 06:08

3 Answers3

6

Shell out:

1.9.3p429 :001 > `ps -p 7544 -o ppid=`.strip
 => "7540"
substars
  • 81
  • 3
  • 1
    The question title specifically says "of a given" process ID. This is the only answer (so far) to the original question. Odd that Ruby can't handle this internally. – Myles Prather Nov 06 '19 at 20:11
5

Process.ppid returns the parent process id. http://ruby-doc.org/core-2.4.1/Process.html#method-c-ppid

a2ikm
  • 455
  • 5
  • 8
2

You can just remember it in a variable:

parent_pid = Process.pid

Process.fork do
  child_pid = Process.pid
  puts parent_pid, child_pid
  # do stuff
  exit
end

Process.wait

# 94791
# 94798

alternatively, if you need the information on the level of the parent process:

parent_pid = Process.pid

child_pid = Process.fork do
  # do stuff
  exit
end

Process.wait
puts parent_pid, child_pid

# 6361
# 6362
Patrick Oscity
  • 53,604
  • 17
  • 144
  • 168