DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Check Whether A Process Is Alive

10.04.2010
| 5749 views |
  • submit to reddit
        Check whether a process is running (actually, present and alive) on a particular machine and/or system using its PID ...

Quick version ...

module Process
  class << self
    def alive?(pid)
      begin
        Process.kill(0, pid)
        true
      rescue Errno::ESRCH
        false
      end
    end
  end
end

A little bit slower version using /proc file system lookup ...

module Process
  class << self
    def alive?(pid)
      Dir['/proc/[0-9]*'].map { |i| i.match(/\d+/)[0].to_i }.include?(pid)
    end
  end
end

Simple use-case:

irb(main):013:0> puts `ps aux | grep -i [t]omboy`
1000     26862  0.0  0.2 103972  9592 ?        Sl   Sep28   0:09 mono /usr/lib/tomboy/Tomboy.exe
=> nil
irb(main):014:0> Process.alive?(26862)
=> true
irb(main):015:0> Process.alive?(12345)
=> false
irb(main):016:0>