Class: Daemon

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

Defined Under Namespace

Classes: LockError

Class Method Summary collapse

Class Method Details

.daemonize(pid_file, log_file = nil) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/daemon.rb', line 8

def self.daemonize(pid_file, log_file = nil)
  exit if fork
  Process.setsid # become session leader
  exit if fork # and exits
  # now in child

  # try to lock before we kill stdin/out
  lock(pid_file)

  if log_file
    log = File.open(log_file, 'a')
  else
    log = '/dev/null'
  end

  # disconnect
  STDIN.reopen '/dev/null'
  STDOUT.reopen log
  STDERR.reopen log
end

.lock(pid_file) ⇒ Object

Raises:



29
30
31
32
33
34
35
36
37
# File 'lib/daemon.rb', line 29

def self.lock(pid_file)
  pf = File.open(pid_file, File::RDWR | File::CREAT)
  raise LockError, pf unless pf.flock(File::LOCK_EX|File::LOCK_NB)
  pf.truncate(0)
  pf.write(Process.pid.to_s + "\n")
  pf.flush

  @pf = pf # keep it open and locked until process exits
end