Class: RFlow::PIDFile

Inherits:
Object
  • Object
show all
Defined in:
lib/rflow/pid_file.rb

Instance Method Summary collapse

Constructor Details

#initialize(path) ⇒ PIDFile

Returns a new instance of PIDFile.



7
8
9
# File 'lib/rflow/pid_file.rb', line 7

def initialize(path)
  @path = path
end

Instance Method Details

#readObject



11
12
13
14
15
16
17
18
19
20
# File 'lib/rflow/pid_file.rb', line 11

def read
  return nil unless File.exist? path
  contents = File.read(path)
  if contents.empty?
    RFlow.logger.warn "Ignoring empty PID file #{path}"
    nil
  else
    contents.to_i
  end
end

#running?Boolean

Returns:

  • (Boolean)


45
46
47
48
49
50
51
52
53
# File 'lib/rflow/pid_file.rb', line 45

def running?
  return false unless exist?
  pid = read
  return false unless pid
  Process.kill(0, pid)
  pid
rescue Errno::ESRCH, Errno::ENOENT
  nil
end

unlinks a PID file at given if it contains the current PID still potentially racy without locking the directory (which is non-portable and may interact badly with other programs), but the window for hitting the race condition is small



59
60
61
# File 'lib/rflow/pid_file.rb', line 59

def safe_unlink
  (current_process? and unlink) rescue nil
end

#signal(sig) ⇒ Object



63
64
65
# File 'lib/rflow/pid_file.rb', line 63

def signal(sig)
  Process.kill(sig, read)
end

#to_sObject



67
68
69
# File 'lib/rflow/pid_file.rb', line 67

def to_s
  File.expand_path(path)
end

#write(pid = $$) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/rflow/pid_file.rb', line 22

def write(pid = $$)
  return unless validate?

  RFlow.logger.debug "Writing PID #{pid} to file '#{to_s}'"
  tmp_path = File.join(File.dirname(path), ".#{File.basename(path)}")
  if File.exist? tmp_path
    RFlow.logger.warn "Deleting stale temp PID file #{tmp_path}"
    File.delete(tmp_path)
  end
  pid_fp = begin
             File.open(tmp_path, File::RDWR|File::CREAT|File::EXCL, 0644)
           rescue Errno::EACCES => e
             RFlow.logger.fatal "Access error while writing temp PID file '#{tmp_path}'"
             RFlow.logger.fatal "Exception #{e.class}: #{e.message}"
             abort
           end
  pid_fp.syswrite("#{pid}\n")
  File.rename(pid_fp.path, path)
  pid_fp.close

  pid
end