How to check for a running process with Ruby?
Asked Answered
C

3

14

I use a scheduler (Rufus scheduler) to launch a process called "ar_sendmail" (from ARmailer), every minute.

The process should NOT be launched when there is already such a process running in order not to eat up memory.

How do I check to see if this process is already running? What goes after the unless below?

scheduler = Rufus::Scheduler.start_new

  scheduler.every '1m' do

    unless #[what goes here?]
      fork { exec "ar_sendmail -o" }
      Process.wait
    end

  end

end
Curtain answered 4/1, 2011 at 13:21 Comment(0)
V
24
unless `ps aux | grep ar_sendmai[l]` != ""
Vizard answered 4/1, 2011 at 13:28 Comment(6)
Thanks! 1 question back: Why the brackets around the "l" of "ar_sendmail"?Curtain
it's to remove the calling process from the grep for a process that matches ar_sendmail - otherwise you'd get a result for 'grep ar_sendmail'Vizard
And if you want to extract the pids: ps aux | grep ar_sendmai[l] | awk '{ print $2 }'Navel
Hi! @stef, what is the approach if I'm using some Rails method (for example Email.send_notifications) instead of above process - fork { exec "ar_sendmail -o" } ?Ama
Don't use unless with != as it results in mental anguish. Instead use if and ==: if something == something_else is more easily understood than unless something != something_else.Rasia
For simpler checks use pidof ar_sendmail.Arte
B
8
unless `pgrep -f ar_sendmail`.split("\n") != [Process.pid.to_s]
Brannon answered 8/4, 2015 at 8:48 Comment(2)
I think this is a much better solution as you don't have to use the bracket thing to exclude the calling process.Overflight
EDIT: Needed the split on \n because of the return structure of pgrep.Brannon
S
1

This looks neater I think, and uses built-in Ruby module. Send a 0 kill signal (i.e. don't kill):

  # Check if a process is running
  def running?(pid)
    Process.kill(0, pid)
    true
  rescue Errno::ESRCH
    false
  rescue Errno::EPERM
    true
  end

Slightly amended from Quick dev tips You might not want to rescue EPERM, meaning "it's running, but you're not allowed to kill it".

Sackbut answered 28/8, 2019 at 8:9 Comment(1)
it returns true, even if the process already in defunct state as reported by psHeraclid

© 2022 - 2024 — McMap. All rights reserved.