Module: HQ::Tools::Lock

Defined in:
lib/hq/tools/lock.rb

Class Method Summary collapse

Class Method Details

.lock(filename, &proc) ⇒ Object



59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/hq/tools/lock.rb', line 59

def self.lock filename, &proc

	while true

		begin

			lock_simple filename, &proc
			return

		rescue Errno::EEXIST => e

			lock_remove filename

		end

	end

end

.lock_remove(filename) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/hq/tools/lock.rb', line 40

def self.lock_remove filename

	# open existing lock file

	File.open filename, File::WRONLY do |file|

		# lock it

		file.flock File::LOCK_EX | File::LOCK_NB \
			or raise "Cannot obtain lock"

		# delete lock file

		File.unlink filename

	end

end

.lock_simple(filename) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/hq/tools/lock.rb', line 5

def self.lock_simple filename

	# create a lock file, will raise EEXIST if it exists

	mode = File::WRONLY | File::CREAT | File::EXCL
	File.open filename, mode do |file|

		# flock it

		file.flock File::LOCK_EX | File::LOCK_NB \
			or raise "Cannot obtain lock"

		begin

			# write our pid

			file.puts $$
			file.flush

			# yield

			yield

		ensure

			# delete lock file

			File.unlink filename

		end

	end

end