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
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
TomDogg
  • 3,803
  • 5
  • 33
  • 60

3 Answers3

24
unless `ps aux | grep ar_sendmai[l]` != ""
stef
  • 14,172
  • 2
  • 48
  • 70
  • Thanks! 1 question back: Why the brackets around the "l" of "ar_sendmail"? – TomDogg Jan 04 '11 at 13:40
  • 9
    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' – stef Jan 04 '11 at 14:14
  • 4
    And if you want to extract the pids: `ps aux | grep ar_sendmai[l] | awk '{ print $2 }'` – phatmann Mar 07 '13 at 18:24
  • 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" } ? – Anikethana Jul 07 '15 at 17:42
  • 2
    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`. – the Tin Man Dec 14 '16 at 16:23
  • For simpler checks use `pidof ar_sendmail`. – Mike Lowery Jul 08 '22 at 19:01
8
unless `pgrep -f ar_sendmail`.split("\n") != [Process.pid.to_s]
dahlberg
  • 81
  • 1
  • 3
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".

Mike
  • 33
  • 6