How can I get pids of all child processes which were started from ruby script?
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.
IO.popen('uname')
IO.popen('uname')
IO.popen('uname')
# Grabbing the pid.
pid = Process.pid
# Get the child pids.
pipe = IO.popen("ps -ef | grep #{pid}")
child_pids = pipe.readlines.map do |line|
parts = line.lstrip.split(/\s+/)
parts[1] if parts[2] == pid.to_s and parts[1] != pipe.pid.to_s
end.compact
# Show the child processes.
puts child_pids
Tested on osx+ubuntu.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With