红宝石列表儿童pids

tig*_*tig 11 ruby process

我怎样才能获得从ruby脚本开始的所有子进程的pid?

Jam*_*mie 12

您可以通过以下方式获取当前流程:

Process.pid
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参阅http://whynotwiki.com/Ruby_/_Process_management.

然后,您可以使用特定于操作的命令来获取子pids.在基于unix的系统上,这将是类似的

# 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
Run Code Online (Sandbox Code Playgroud)

在osx + ubuntu上测试.

我承认这可能不适用于所有unix系统,因为我认为ps -ef不同unix风格的输出略有不同.

  • 只需几美分:"ps o pid = --ppid#{pid}"可能比"ps -ef | grep#{pid}"更方便,在这种情况下你不必过滤掉不需要的行和字段. (5认同)

Col*_*tin 6

Process.fork响应生成的子进程的PID.在生成孩子时,只需在数组中跟踪它们.见http://ruby-doc.org/core/classes/Process.html#M003148.