Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby list child pids

Tags:

process

ruby

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

like image 971
tig Avatar asked Dec 18 '09 18:12

tig


2 Answers

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.

like image 175
Jamie Avatar answered Nov 16 '22 17:11

Jamie


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.

like image 6
Colin Curtin Avatar answered Nov 16 '22 17:11

Colin Curtin