Skip to content

Commit

Permalink
first commit
Browse files Browse the repository at this point in the history
  • Loading branch information
simon-engledew committed Oct 29, 2008
0 parents commit 1b8b8fd
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 0 deletions.
24 changes: 24 additions & 0 deletions README
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

42 changes: 42 additions & 0 deletions process_lock.rb
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

0 comments on commit 1b8b8fd

Please sign in to comment.