From 1081a322f1b846fcddb3cb77f068e2e818f9d73f Mon Sep 17 00:00:00 2001 From: Jacob Vosmaer Date: Thu, 27 Aug 2015 16:35:00 +0200 Subject: Properly daemonize the mail_room process The old invocation only worked by accident because we have a '&' somewhere in the init script for expediency. When ran from a terminal, the mail_room daemon process ended up in the session of the terminal. This commit adds a small wrapper that tries to do the textbook daemonization steps (double fork, setsid etc.) while also taking care that the pidfile is written before the 'start' process exits. --- bin/daemon_with_pidfile | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100755 bin/daemon_with_pidfile (limited to 'bin/daemon_with_pidfile') diff --git a/bin/daemon_with_pidfile b/bin/daemon_with_pidfile new file mode 100755 index 00000000000..f138c27a0e2 --- /dev/null +++ b/bin/daemon_with_pidfile @@ -0,0 +1,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) -- cgit v1.2.3