Created
December 6, 2009 02:33
-
-
Save apeckham/250003 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class PidFile | |
attr_reader :path | |
def initialize(path) | |
@path = path | |
end | |
def write | |
file = File.open(@path, "w") | |
file << Process.pid | |
file.close | |
end | |
def unlink | |
File.unlink(@path) | |
end | |
def running? | |
return false unless File.exist?(@path) | |
return false unless pid = read_from_file | |
begin | |
Process.kill(0, pid) | |
return true | |
rescue Errno::ESRCH | |
return false | |
end | |
end | |
def if_not_running | |
unless running? | |
write | |
yield | |
unlink | |
end | |
end | |
private | |
def read_from_file | |
lines = File.readlines(@path) | |
return if lines.empty? | |
lines.first.chomp.to_i | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment