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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With