通过Ruby中的pid获取进程状态

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

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

我不知道一个可移植的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. 

我在寻找同样的事情。 令人遗憾的是,ProcessStatus似乎无法从实时pid初始化。 如果你想做一些安全的定时杀死子进程的事情,这是至关重要的。

在任何情况下,如果你在Linux上,它是/proc/$pid/status的第二行: status_line = File.open("/proc/#{pid}/status") {|f| f.gets; f.gets } status_line = File.open("/proc/#{pid}/status") {|f| f.gets; f.gets }

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

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

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

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

 termoutput=%x[#{outputstring}] 

如果需要,我可以显示它,或者只是保持输出清洁并​​对我通过调用找到的状态起作用。