-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
0 parents
commit 1b8b8fd
Showing
2 changed files
with
66 additions
and
0 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
Just a simple class to determine if another process has already locked a file on a unix filesystem. | ||
|
||
Example: | ||
|
||
IRB 1>> | ||
p = ProcessLock.new('example.tmp') | ||
p.owner? | ||
=> false | ||
p.aquire! | ||
=> true | ||
p.owner? | ||
=> true | ||
|
||
IRB 2>> | ||
q = ProcessLock.new('example.tmp') | ||
p.owner? | ||
=> false | ||
p.aquire! | ||
=> false | ||
p.alive? | ||
=> true | ||
|
||
Copyright (c) 2008 Simon Engledew, released under the MIT license | ||
|
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
class ProcessLock | ||
|
||
def initialize(filename) | ||
FileUtils.touch(@filename = filename) | ||
end | ||
|
||
def aquire! | ||
File.open(@filename, 'r+') do |f| | ||
lock(f, false) do | ||
f.truncate(f.write(Process.pid)) | ||
return true | ||
end | ||
end | ||
return false | ||
end | ||
|
||
def alive? | ||
pid = read | ||
return pid > 0 ? Process.kill(0, pid) > 0 : false | ||
rescue | ||
return false | ||
end | ||
|
||
def owner? | ||
pid = read | ||
pid and pid > 0 and pid == Process.pid | ||
end | ||
|
||
def read | ||
File.open(@filename, 'r+'){|f|lock(f){f.read.to_i}} | ||
end | ||
|
||
private | ||
|
||
def lock(file, blocking = true) | ||
file.flock(blocking ? File::LOCK_EX : File::LOCK_EX | File::LOCK_NB) | ||
return yield | ||
ensure | ||
file.flock(File::LOCK_UN) | ||
end | ||
|
||
end |