ruby 列表子 pids

标签 ruby process

如何获取从 ruby​​ 脚本启动的所有子进程的 pids?

最佳答案

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

Process.pid

参见 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

在 osx+ubuntu 上测试。

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

关于ruby 列表子 pids,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1929849/

相关文章:

Ruby 的 open-uri 和 cookies

ruby - 全部大写到正常大小写

java - 两个进程之间的数据流

linux - 从 "ps"获取完整结果

c - "Detaching after fork from child process 15***"的含义?

ruby - 从具有未知键的嵌套哈希中选择一个值

ruby - 嵌套异常中的回溯

ruby-on-rails - 自引用问题 has_many :through associations in Rails

C++ - 在不使用系统从批处理文件转换的情况下运行程序

java - 从 Java 运行 "sandbox"内的可执行文件