Module: Lock

Defined in:
lib/lock.rb

Class Method Summary collapse

Class Method Details

.create(name) ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/lock.rb', line 53

def Lock::create name
  wait_for(name)
  lockfn = local(name)
  if File.exist?(lockfn)
    $stderr.print "\nERROR: Can not steal #{lockfn}"
    exit 1
  end
  File.open(lockfn, File::RDWR|File::CREAT, 0644) do |f|
    f.flock(File::LOCK_EX)
    f.print(Process.pid)
  end
end

.local(name) ⇒ Object



24
25
26
# File 'lib/lock.rb', line 24

def self.local name
  ENV['HOME']+"/."+name.gsub("/","-")+".lck"
end

.lock_pid(name) ⇒ Object



28
29
30
31
32
33
34
35
# File 'lib/lock.rb', line 28

def self.lock_pid name
  lockfn = local(name)
  if File.exist?(lockfn)
    File.read(lockfn).to_i
  else
    0
  end
end

.locked?(name) ⇒ Boolean

Returns:

  • (Boolean)


37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/lock.rb', line 37

def self.locked? name
  lockfn = local(name)
  pid = lock_pid(name)
  if File.exist?("/proc/#{pid}")
    true
  else
    # the program went away - remove any 'stale' lock
    begin
      File.unlink(lockfn)
    rescue Errno::ENOENT
      # ignore error when the lock file went missing
    end
    false # --> no longer locked
  end
end

.release(name) ⇒ Object



82
83
84
85
86
87
88
89
90
91
92
93
# File 'lib/lock.rb', line 82

def Lock::release name
  lockfn = local(name)
  if Process.pid == lock_pid(name)
    begin
      File.unlink(lockfn) # PID expired
    rescue Errno::ENOENT
      # ignore error when the lock file went missing
    end
  else
    $stderr.print "\nERROR: can not release #{lockfn} because it is not owned by me"
  end
end

.wait_for(name) ⇒ Object



66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/lock.rb', line 66

def Lock::wait_for name
  lockfn = local(name)
  begin
    status = Timeout::timeout(180) { # 3 minutes
      while locked?(name)
        $stderr.print("\nWaiting for lock #{lockfn}...")
        sleep 2
      end
    }
  rescue Timeout::Error
    $stderr.print "\nERROR: Timed out, but I can not steal #{lockfn}"
    exit 1
  end
  # yah! lock is released
end