5

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

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

4

3 回答 3

2

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

无论如何,/proc/$pid/status如果你在 Linux 上,这是第二行: status_line = File.open("/proc/#{pid}/status") {|f| f.gets; f.gets }

很可能比任何涉及外部程序的东西都要快得多。

于 2015-04-22T13:15:59.833 回答
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.
于 2012-05-15T00:07:35.523 回答
0

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

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

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

termoutput=%x[#{outputstring}]

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

于 2013-07-30T19:00:22.050 回答