Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find a process ID by name

Tags:

unix

ruby

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

I am sending SIGUSR2 to a process whose 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
like image 880
Joel Avatar asked Aug 26 '10 10:08

Joel


1 Answers

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.

like image 178
AboutRuby Avatar answered Sep 30 '22 14:09

AboutRuby