Class: Daemonic::Pidfile

Inherits:
Object
  • Object
show all
Includes:
Logging, FileUtils
Defined in:
lib/daemonic/pidfile.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Logging

#logger

Constructor Details

#initialize(options = {}) ⇒ Pidfile

Returns a new instance of Pidfile.



10
11
12
13
14
# File 'lib/daemonic/pidfile.rb', line 10

def initialize(options = {})
  @pid      = options.fetch(:pid)
  @config   = options.fetch(:config)
  @index    = options[:index]
end

Instance Attribute Details

#configObject (readonly)

Returns the value of attribute config.



8
9
10
# File 'lib/daemonic/pidfile.rb', line 8

def config
  @config
end

#indexObject (readonly)

Returns the value of attribute index.



8
9
10
# File 'lib/daemonic/pidfile.rb', line 8

def index
  @index
end

#pidObject (readonly)

Returns the value of attribute pid.



8
9
10
# File 'lib/daemonic/pidfile.rb', line 8

def pid
  @pid
end

Instance Method Details

#cleanObject



35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/daemonic/pidfile.rb', line 35

def clean
  if File.exist?(filename)
    existing_pid = File.open(filename, 'r').read.chomp
    if existing_pid == pid.to_s
      debug "Cleaning up my own pid file at `#{filename}`"
      rm(filename)
    else
      debug "Pid file `#{filename}` did not belong to me, so not cleaning. I am #{Process.pid}, and the pid file says #{existing_pid}"
    end
  else
    debug "Pid file disappeared from `#{filename}`"
  end
end

#writeObject



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/daemonic/pidfile.rb', line 16

def write
  mkdir_p(File.dirname(filename))

  if File.exist?(filename)
    existing_pid = File.open(filename, 'r').read.chomp
    running = Process.getpgid(existing_pid) rescue false
    if running
      fatal "Error: PID file already exists at `#{filename}` and a process with PID `#{existing_pid}` is running"
      exit 1
    else
      debug "Warning: cleaning up stale pid file at `#{filename}`"
      write!
    end
  else
    debug "Writing pidfile #{filename} with pid #{pid}"
    write!
  end
end