【问题标题】:Get process status by pid in Ruby在Ruby中通过pid获取进程状态
【发布时间】:2012-05-14 19:38:16
【问题描述】:

有没有办法根据 Ruby 中的 PID 获取进程的子进程状态?

例如,在 Python 中,您可以执行 psutil.Process(pid).status

【问题讨论】:

  • 我相信 Process Module 里面有你需要的东西:ruby-doc.org/core-1.9.3/Process.html
  • 您需要在哪些操作系统上使用它?
  • @vlasits 进程模块没有任何方法可以获取正在运行的进程的状态,只有退出的进程。

标签: ruby process-management


【解决方案1】:

我也在寻找同样的东西。很遗憾 ProcessStatus 似乎无法从实时 pid 中初始化。如果您想做安全定时杀死子进程之类的事情,这是至关重要的。

无论如何, 如果您使用的是 Linux,则它是 /proc/$pid/status 中的第二行。: status_line = File.open("/proc/#{pid}/status") {|f| f.gets; f.gets }

很可能比涉及外部程序的任何事情都快得多。

【讨论】:

  • 简单而优雅的解决方案,避免依赖外部程序(和脱壳),谢谢。
【解决方案2】:

我不知道一种可移植的 ruby​​ 方法来获取正在运行的进程的进程状态。您可以执行Process.wait 并检查$?.exitstatus,但这看起来不像您想要的。对于 posix 解决方案,您可以使用

`ps -o state -p #{pid}`.chomp

获取 ps 为进程状态生成的字母代码

PROCESS STATE CODES
Here are the different values that the s, stat and state output specifiers
(header "STAT" or "S") will display to describe the state of a process.
D    Uninterruptible sleep (usually IO)
R    Running or runnable (on run queue)
S    Interruptible sleep (waiting for an event to complete)
T    Stopped, either by a job control signal or because it is being traced.
W    paging (not valid since the 2.6.xx kernel)
X    dead (should never be seen)
Z    Defunct ("zombie") process, terminated but not reaped by its parent.

【讨论】:

  • 也许我遗漏了什么,但 -o=state= 不应该是 -o state 吗?使用等号在我的 linux 机器上不起作用。
  • @BenCrowell 我不知道为什么我在 10 年前写了这个。等号可用于重命名列标题,但在这里无关紧要。将原文修改为正确。谢谢。
【解决方案3】:

在 OS X 上,我设置了一个字符串:

outputstring="ps -O=S -p #{mypid}"

然后在 %x 调用中执行它:

termoutput=%x[#{outputstring}]

如果需要,我可以显示它,或者只是保持输出干净并根据我在调用中找到的状态采取行动。

【讨论】:

    猜你喜欢
    • 2011-05-10
    • 1970-01-01
    • 1970-01-01
    • 2013-02-05
    • 2014-12-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多