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

Solution 1:

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

Solution 2:

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
>> 

Solution 3:

@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.