Find process id by name

How to find pid by name or in the full command line in Ruby without calling an external executable?

I am sending SIGUSR2 to a process whose command line contains ruby job.rb I would like to do the following without calling pgrep :

 uid = Process.uid pid = `pgrep -f "ruby job.rb" -u #{uid}`.split("\n").first.to_i Process.kill "USR2", pid 
+6
ruby unix
source share
3 answers

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

Disclaimer: I do not use Ruby, I can not confirm whether this works.

+4
source share

How to do this depends on your operating system. Assuming Linux, you can manually scan the / proc file system and look for the correct command line. However, this is the same as pgrep does, 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 looking in / proc.

+7
source share

Debian based systems find pid with the pidof command.

Some kill completion function with ruby:

 def killPid(cmd) pid=exec("pidof #{cmd}") Process.kill "USR2", pid end 
+1
source share

All Articles