Showing posts with label processes. Show all posts
Showing posts with label processes. Show all posts

Monday, 7 September 2009

More fun with pid files

Another way of handling pid files is a more ruby like way is:
#!/usr/bin/env ruby

class PidFile
def initialize(filename, &code)
unless set_pid(filename)
raise RuntimeError.new("The process is already running")
end

code.call

File.delete(filename)
end

private

def set_pid(filename)
# Same code as before
end
end

And call it thus
PidFile.new("/var/run/app.pid") do
puts "What we want to do"
end

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