2012-05-14 37 views
5

有沒有一種方法可以根據Ruby中的PID獲取進程的子進程狀態?通過Ruby中的pid獲取進程狀態

例如,在Python中,你可以做psutil.Process(PID).STATUS

+2

我相信流程模塊有你需要的東西:http://www.ruby-doc.org/core-1.9.3/Process.html – vlasits

+0

什麼操作系統你需要這個工作? – Phrogz

+1

@vlasits進程模塊沒有任何獲取正在運行的進程狀態的方法,只有已退出的進程。 – dbenhur

回答

2

我不知道便攜式紅寶石方法來獲取正在運行的進程的進程狀態。你可以做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. 
0

在OS X上,我設置的字符串:

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

然後執行它在%x呼叫中:

termoutput=%x[#{outputstring}] 

如果需要,我可以展示這些信息,或者只是保持輸出清晰,並在通話時找到的國家採取行動。

2

我在找同樣的東西。這是一個恥辱ProcessStatus似乎無法從活動pid初始化。如果你想做一個像安全的定時殺死一個子進程的東西,這是至關重要的。

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

最有可能比涉及外部程序什麼太大快得多。

+0

簡單而優雅的解決方案,以避免依賴外部程序(和脫殼),謝謝。 – Navarro