File: flock.rb

package info (click to toggle)
libnora-ruby 1%3A0.0.20041021-4
  • links: PTS
  • area: main
  • in suites: squeeze
  • size: 408 kB
  • ctags: 726
  • sloc: ruby: 5,186; ansic: 669; makefile: 248; sql: 10
file content (45 lines) | stat: -rwxr-xr-x 1,043 bytes parent folder | download | duplicates (5)
1
2
3
4
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
39
40
41
42
43
44
45
# Web::Persistent::Lock::Flock
# Copyright(c) 2002 MoonWolf <moonwolf@moonwolf.com>
module Web
  class Persistent
    module Lock
      class Flock
        def initialize(persistent_id, options={})
          @persistent_id = persistent_id
          @dir    = options[:dir]    || '/tmp'
          prefix  = options[:prefix] || 'lock_'
          @path   = File.join(@dir, prefix + persistent_id)
          @f      = nil
          @locked = false
        end

        def lock
          @locked = true
          @f = @f || open(@path,'w')
          @f.flock(File::LOCK_EX)
          if block_given?
            yield
            unlock
          end
        end

        def unlock
          raise unless @f
          @f.flock(File::LOCK_UN)
          @locked = false
        end

        def delete
          begin
            File.unlink(@path)
            if @f
              @f.close
              @f = nil
            end
          rescue Errno::ENOENT
          end
        end
      end # Flock
    end # Lock
  end # Persistent
end # Web