Created
May 2, 2012 09:47
-
-
Save ebisawa/2575606 to your computer and use it in GitHub Desktop.
Symlink Locker
This file contains hidden or 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 Locker | |
def initialize(lockname) | |
@lockname = lockname | |
@lockpath = "/tmp/#{lockname}" | |
@mylock = "#{@lockpath}.#{Process.pid}" | |
@havelock = false | |
end | |
def lock | |
do_lock | |
if block_given? | |
yield | |
unlock | |
end | |
end | |
def unlock | |
raise "I don't have lock" if !@havelock | |
FileUtils.rm(@lockpath) | |
FileUtils.rm(@mylock) | |
@havelock = false | |
end | |
private | |
def do_lock | |
if File.exist?(@lockpath) | |
return false | |
end | |
begin | |
FileUtils.touch(@mylock) | |
FileUtils.ln_s(@mylock, @lockpath) | |
rescue Errno::ENOTDIR | |
# failed to obtain lock | |
FileUtils.rm(@mylock) | |
else | |
@havelock = true | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment