rubyprocessprocess-management

Getting the parent id of a given process in Ruby


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.


Solution

  • 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