How can I check from Ruby whether a process with a certain pid is running?

一世执手 提交于 2019-12-02 17:15:54

If it's a process you expect to "own" (e.g. you're using this to validate a pid for a process you control), you can just send sig 0 to it.

>> Process.kill 0, 370
=> 1
>> Process.kill 0, 2
Errno::ESRCH: No such process
    from (irb):5:in `kill'
    from (irb):5
>> 
tonystubblebine

The difference between the Process.getpgid and Process::kill approaches seems to be what happens when the pid exists but is owned by another user. Process.getpgid will return an answer, Process::kill will throw an exception (Errno::EPERM).

Based on that, I recommend Process.getpgid, if just for the reason that it saves you from having to catch two different exceptions.

Here's the code I use:

begin
  Process.getpgid( pid )
  true
rescue Errno::ESRCH
  false
end

@John T, @Dustin: Actually, guys, I perused the Process rdocs, and it looks like

Process.getpgid( pid )

is a less violent means of applying the same technique.

balu

For child processes, other solutions like sending a signal won't behave as expected: they will indicate that the process is still running when it actually exited.

You can use Process.waitpid if you want to check on a process that you spawned yourself. The call won't block if you're using the Process::WNOHANG flag and nil is going to be returned as long as the child process didn't exit.

Example:

pid = Process.spawn('sleep 5')
Process.waitpid(pid, Process::WNOHANG) # => nil
sleep 5
Process.waitpid(pid, Process::WNOHANG) # => pid

If the pid doesn't belong to a child process, an exception will be thrown (Errno::ECHILD: No child processes).

The same applies to Process.waitpid2.

This is how I've been doing it:

def alive?(pid)
  !!Process.kill(0, pid) rescue false
end

You can try using

Process::kill 0, pid

where pid is the pid number, if the pid is running it should return 1.

Under Linux you can obtain a lot of attributes of running programm using proc filesystem:

File.read("/proc/#{pid}/cmdline")
File.read("/proc/#{pid}/comm")

A *nix-only approach would be to shell-out to ps and check if a \n (new line) delimiter exists in the returned string.

Example IRB Output

1.9.3p448 :067 > `ps -p 56718`                                                          
"  PID TTY           TIME CMD\n56718 ttys007    0:03.38 zeus slave: default_bundle   \n"

Packaged as a Method

def process?(pid)  
  !!`ps -p #{pid.to_i}`["\n"]
end
Wilson Silva

I've dealt with this problem before and yesterday I compiled it into the "process_exists" gem.

It sends the null signal (0) to the process with the given pid to check if it exists. It works even if the current user does not have permissions to send the signal to the receiving process.

Usage:

require 'process_exists'

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