Friday 4 September 2009

Checking for processes and pid files

If you have a periodic task that might still be running when you try to run it and don't want both copies of the program running then you need to create a pid file and check it when your process starts.
# Returns true if it was able to create the pid file

def set_pid(filename)
if File.exist?(filename)
File.open(filename, "r").each do |l|
old_pid = l.chomp.to_i

begin
Process.kill(0, old_pid)
# The process is running
return false
rescue Errno::EPERM
# The process is running and you don't have permission
return false
rescue
# the process is not running or something
end
end

File.delete(filename)
end

# Create the new process
f = File.new(filename, "w")
f.puts $$
f.close

return true
end

At the start of you program call it as follows
unless set_pid("/var/run/app.pid")
puts "This process is already running!"
exit
end

This is good for OS X and Linux, not sure if it will work for Windows. Probably will

No comments:

Post a Comment