A daemon is a process that runs in the background as a system process.

In ruby we can use Process.daemon to put a process into the background. “ri Process.daemon” says:

Detach the process from controlling terminal and run in the background as system daemon. Unless the argument nochdir is true (i.e. non false), it changes the current working directory to the root (“/”). Unless the argument noclose is true, daemon() will redirect standard input, standard output and standard error to /dev/null.

In this example the USR1 signal is trapped that it can say hi to the standard output stream. If you issue a “kill -USR1 " to the process then the daemon process will write a message to the log file. The process starts by forking itself. The parent process immediately exits and the child process goes to sleep forever.

If you copy this into a file and run it from ruby. Your shell will immediately return to your prompt. If you run “ps | grep ruby” you will find that there is still a process running in the background. This is your daemon process.

All ouput is currently redirecting to a log file. Try to run “tail -f /tmp/daemon.log” and you will see all the output from the daemon process.

$ tail -f /tmp/daemon.log

With tail still running, open another terminal window and use kill to send a USR1 signal to your daemon process. “kill -USR1 ". You'll find that the daemon process responds by saying HI then goes back to sleep.

$ kill -USR1 <PID>


comments powered by Disqus