开发者

ruby list child pids

How can I get pids of all chil开发者_开发知识库d 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.


Can be also done using sys-proctable gem:

require 'sys/proctable'

Sys::ProcTable.ps.select{ |pe| pe.ppid == $$ }


This is actually quiet complicated and is platform specific. You actually cannot find all sub-processes if they deliberately try to hide.

If you want to just kill spawned processes there are many options. For a test framework I chose two: 1. spawn processes with pgid => true 2. insert variable MY_CUSTOM_COOKIE=asjdkahf, then find procs with that cookie in environment and kill it.

FYI using ps to find out process hierarchy is very unreliable. If one process in the chain exits, then its sub-processes get a parent pid of 1 (on linux at least). So it's not worth implementing.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜