summaryrefslogtreecommitdiff
path: root/bin/daemon_with_pidfile
blob: f138c27a0e2b85374a5f874a633163b864e04eb1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#!/usr/bin/env ruby
# daemon_with_pidfile
#
# Daemonize, write a pidfile, and exec the remainder of the command line.

def main(pidfile, cmd)
  if middle_pid = Process.fork
    # outer process
    # Do not exit the outer process before the middle process finishes
    Process.waitpid(middle_pid)
    exit $?.exitstatus
  end

  if final_pid = Process.fork
    # middle process
    open(pidfile, 'w') { |f| f.puts final_pid }
    exit
  end

  # Standard daemon things: become session leader, ignore SIGHUP, close stdin.
  Signal.trap("HUP", "IGNORE")
  Process.setsid
  IO.new(0).close

  exec(*cmd)
end

if ARGV.count < 2
  abort "Usage: #$0 pidfile command [args...]"
end

pidfile = ARGV.shift
main(pidfile, ARGV)