Class: ProcessLock
- Inherits:
-
Object
show all
- Defined in:
- lib/process_lock.rb,
lib/process_lock/version.rb
Defined Under Namespace
Classes: AlreadyLocked, NotLocked
Constant Summary
collapse
- VERSION =
"0.1.1"
Instance Attribute Summary collapse
Instance Method Summary
collapse
Constructor Details
#initialize(filename) ⇒ ProcessLock
Returns a new instance of ProcessLock.
14
15
16
17
18
19
20
21
22
23
|
# File 'lib/process_lock.rb', line 14
def initialize(filename)
@filename = filename
if defined?(Rails) and Rails.root and (File.basename(filename) == @filename)
@filename = File.join(Rails.root, 'tmp', 'pids', filename)
unless filename =~ /\./
@filename << '.pid'
end
end
FileUtils.touch(@filename)
end
|
Instance Attribute Details
#filename ⇒ Object
Returns the value of attribute filename.
6
7
8
|
# File 'lib/process_lock.rb', line 6
def filename
@filename
end
|
Instance Method Details
#acquire ⇒ Object
38
39
40
41
42
43
44
45
46
47
48
|
# File 'lib/process_lock.rb', line 38
def acquire
result = acquire_without_block
if result and block_given?
begin
result = yield
ensure
release
end
end
result
end
|
#acquire! ⇒ Object
25
26
27
28
29
30
31
32
33
34
35
36
|
# File 'lib/process_lock.rb', line 25
def acquire!
result = acquired = acquire_without_block
if acquired and block_given?
begin
result = yield
ensure
release
end
end
raise(AlreadyLocked.new('Unable to acquire lock')) unless acquired
result
end
|
#alive? ⇒ Boolean
68
69
70
71
72
73
|
# File 'lib/process_lock.rb', line 68
def alive?
pid = read
return pid > 0 ? Process.kill(0, pid) > 0 : false
rescue
return false
end
|
#owner? ⇒ Boolean
75
76
77
78
|
# File 'lib/process_lock.rb', line 75
def owner?
pid = read
pid and pid > 0 and pid == Process.pid
end
|
#read ⇒ Object
80
81
82
|
# File 'lib/process_lock.rb', line 80
def read
open_and_lock{|f| f.read.to_i}
end
|
#release ⇒ Object
57
58
59
60
61
62
63
64
65
66
|
# File 'lib/process_lock.rb', line 57
def release
acquired = false
open_and_lock do |f|
acquired = owner?
if acquired
f.truncate(f.write(''))
end
end
acquired
end
|
#release! ⇒ Object
50
51
52
53
54
55
|
# File 'lib/process_lock.rb', line 50
def release!
unless release
raise NotLocked.new('Unable to release lock (probably did not own it)')
end
true
end
|