How do I ensure a process is running, even if it kills itself? (it needs to be restarted then)

Posted by le_me on Super User See other posts from Super User or by le_me
Published on 2012-11-29T13:57:08Z Indexed on 2012/12/02 17:08 UTC
Read the original article Hit count: 323

Filed under:
|
|
|
|

I'm using linux. I want a process (an irc bot) to run every time I start the computer. But I've got a problem: The network is bad and it disconnects often, so I need to manually restart the bot a few times a day. How do I automate that?

Additional information: The bot creates a pid file, called bot.pid The bot reconnects itself, but only a few times. The network is too bad, so the bot kills itself sometimes because it gets no response.

What I do currently (aka my approach ;) ) I have a cron job executing startbot.rb every 5 minutes. (The script itself is in the same directory as the bot)

The script:

#!/usr/bin/ruby
require 'fileutils'

if File.exists?(File.expand_path('tmp/bot.pid'))
  @pid = File.read(File.expand_path('tmp/bot.pid')).chomp!.to_i
  begin
    raise "ouch" if Process.kill(0, @pid) != 1
  rescue
    puts "Removing abandoned pid file"
    FileUtils.rm(File.expand_path('tmp/bot.pid'))
    puts "Starting the bot!"
    Kernel.exec(File.expand_path('./bot.rb'))
  else
    puts "Bot up and running!"
  end
else
  puts "Starting the bot!"
  Kernel.exec(File.expand_path('./bot.rb'))
end

What this does: It checks if the pid file exists, if that's true it checks if kill -s 0 BOT_PID == 1 (if the bot's running) and starts the bot if one of the two checks fail/are not true.

My approach seems to be quite dirty so how do I do it better?

© Super User or respective owner

Related posts about linux

Related posts about boot