Method: Main::Daemon#detach!

Defined in:
lib/main/daemon.rb

#detach!(&block) ⇒ Object



434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
# File 'lib/main/daemon.rb', line 434

def detach!(&block)
# setup a pipe to relay the grandchild pid through
#
  a, b = IO.pipe

# in the parent we wait for the pid, wait on our child to avoid zombies, and
# then exit
#
  if fork
    b.close
    pid = Integer(a.read.strip)
    a.close
    block.call(pid) if block
    Process.waitall
    exit!
  end

# the child simply exits so it can be reaped - avoiding zombies.  the pipes
# are inherited in the grandchild
#
  if fork
    exit!
  end

# finally, the grandchild sends it's pid back up the pipe to the parent is
# aware of the pid
#
  a.close
  b.puts(Process.pid)
  b.close

# might as well nohup too...
#
  Process::setsid rescue nil
end