views:

249

answers:

2

How can I get pids of all child processes which were started from ruby script?

+3  A: 

Process.fork responds with the PID of the child spawned. Just keep track of them in an array as you spawn children. See http://ruby-doc.org/core/classes/Process.html#M003148.

Colin Curtin
It would be a good variant but in my case I have a method yielding a block and the only way to track all calls to fork, system, spawn, backtrick and others it to chain those methods through pid counter, but I hoped that there is easier way to get children pids
tig
+2  A: 

You can get the current process with:

Process.pid

see http://whynotwiki.com/Ruby_/_Process_management for further details.

Then you could use operating specific commands to get the child pids. On unix based systems this would be something along the lines of

# Creating 3 child processes.
pipe = IO.popen('uname')
pipe = IO.popen('uname')
pipe = IO.popen('uname')

# Grabbing the pid.
pid= Process.pid

# Get the child pids.
child_pids = Array.new
pipe = IO.popen("ps -ef | grep #{pid}")
pipe.readlines.each { |line|
    parts = line.split(/\s+/)
    if (parts[3] == pid.to_s && parts[2] != pipe.pid.to_s) then
            child_pids.push parts[2]
    end
}

# Show the child processes.
puts child_pids

I admit that this probably doesn't work on all unix systems as I believe the output of ps -ef varies slightly on different unix flavors.

Jamie
`Process.pid` returns the pid of the current process, not the parent process. To get the parent process pid, do `Process.ppid`.
dvyjones
Just an error in the comments we need the current process, as this will be the parent of the child processes.
Jamie