tags:

views:

43

answers:

2

How can I find a pid by name or full command line in Ruby, without calling an externally executable?

In my example below, I am sending a SIGUSR2 to a process who's command line contained "ruby job.rb". I would like to do the following without the call to pgrep:

uid = Process.uid
pid = `pgrep -f "ruby job.rb" -u #{uid}`.split("\n").first.to_i
Process.kill "USR2", pid
+2  A: 

How to do this depends on your operating system. Assuming Linux, you can manually crawl the /proc filesystem and look for the right command line. However, this is the same thing that pgrep is doing, and will actually make the program less portable.

Something like this might work.

def get_pid(cmd)
  Dir['/proc/[0-9]*/cmdline'].each do|p|
    if File.read(p) == cmd
      Process.kill( "USR2", p.split('/')[1] )
    end
  end
end

Just be careful poking around in /proc.

AboutRuby
Speaking of *less portable* - this does not work on Solaris. You are presuming that you are running on Linux here.
Beano
Yes, I did say "assuming Linux."
AboutRuby
+1 Accepted another answer, but I like this too. A reminder of just how much you can do on Linux in any language with just the file-system
Joel
+1  A: 

A quick google search came up with sys_proctable, which should let you do this in a portable way.

Disclaimer: I don't use Ruby, can't confirm if this works.

Hasturkun