Class: PidFileBlock

Inherits:
Object
  • Object
show all
Defined in:
lib/pid_file_block.rb,
lib/pid_file_block/version.rb,
lib/pid_file_block/application.rb,
lib/pid_file_block/process_exists_error.rb

Defined Under Namespace

Modules: Version Classes: Application, ProcessExistsError

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(piddir: '/run', pidfile:) ⇒ PidFileBlock

Returns a new instance of PidFileBlock.



8
9
10
11
# File 'lib/pid_file_block.rb', line 8

def initialize(piddir: '/run', pidfile:)
  pidfile ||= File.basename($0, '.*')
  @pid_file_full_name = File.join(piddir, pidfile)
end

Instance Attribute Details

#pid_file_full_nameObject (readonly)

Returns the value of attribute pid_file_full_name.



6
7
8
# File 'lib/pid_file_block.rb', line 6

def pid_file_full_name
  @pid_file_full_name
end

Instance Method Details

#kill(signal: "TERM") ⇒ Object



64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/pid_file_block.rb', line 64

def kill(signal: "TERM")
    pid = nil
    File.open(@pid_file_full_name, 'r') do |f|
      f.flock(File::LOCK_SH)
      pid_str = f.read
      begin
        pid = Integer(pid_str)
      rescue ArgumentError
        return false
      end    
    end
    Process.kill(signal, pid)
    return pid
end

#openObject



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
# File 'lib/pid_file_block.rb', line 13

def open
  loop do
    begin
      File.open(@pid_file_full_name, 'r') do |f|
        f.flock(File::LOCK_EX)
        if process_running?(f)
          # f.flock(File::LOCK_UN)
          raise PidFileBlock::ProcessExistsError
        end
        unlink_pid_file_if_exists
      end
    rescue Errno::ENOENT
    end
    begin
      File.open(@pid_file_full_name,
                File::Constants::RDWR|File::Constants::CREAT|File::Constants::EXCL) do |f|
        f.flock(File::LOCK_EX)
        if process_running?(f)
          f.flock(File::LOCK_UN)
          raise PidFileBlock::ProcessExistsError
        end
        write_pid(f)
        f.flock(File::LOCK_UN)
      end
      break
    rescue Errno::EEXIST
    end
  end
  yield
  unlink_pid_file_if_exists
end

#releaseObject



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/pid_file_block.rb', line 45

def release
  our_pid = $$
  File.open(@pid_file_full_name, 'r') do |f|
    f.flock(File::LOCK_SH)
    file_pid_str = f.read
    begin
      file_pid = Integer(file_pid_str)
    rescue ArgumentError
      return false
    end      
    if file_pid == our_pid
      unlink_pid_file_if_exists
      return true
    else
      return false
    end
  end
end