Get process status by pid in Ruby

自闭症网瘾萝莉.ら 提交于 2020-01-01 10:45:06

问题


Is there a way to get a process's child process status based on its PID in Ruby?

For example, in Python you can do psutil.Process(pid).status


回答1:


I don't know of a portable ruby method to get process state of a running process. You can do Process.wait and check $?.exitstatus, but that doesn't look like what you want. For a posix solution, you could use

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

to get the letter code ps produces for process state

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.



回答2:


I was looking for the same thing. It's a shame ProcessStatus doesn't seem to be able to get initialized from a live pid. This is vital stuff if you want to do anything like a safe timed kill of a child process.

In any case, it's the second line in /proc/$pid/status if you're on Linux.: status_line = File.open("/proc/#{pid}/status") {|f| f.gets; f.gets }

Most likely much much faster than anything involving an external program.




回答3:


On OS X, I setup a string:

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

then execute it in a %x call:

termoutput=%x[#{outputstring}]

I can display that if needed, or just keep the output clean and act on the State I found with the call.



来源:https://stackoverflow.com/questions/10589935/get-process-status-by-pid-in-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!