#!/usr/bin/env ruby# daemon_with_pidfile## Daemonize, write a pidfile, and exec the remainder of the command line.defmain(pidfile,cmd)ifmiddle_pid=Process.fork# outer process# Do not exit the outer process before the middle process finishesProcess.waitpid(middle_pid)exit$?.exitstatusendiffinal_pid=Process.fork# middle processopen(pidfile,'w'){|f|f.putsfinal_pid}exitend# Standard daemon things: become session leader, ignore SIGHUP, close stdin.Signal.trap("HUP","IGNORE")Process.setsidIO.new(0).closeexec(*cmd)endifARGV.count<2abort"Usage: #$0 pidfile command [args...]"endpidfile=ARGV.shiftmain(pidfile,ARGV)