Wednesday, 2 May 2012

daemonize - Running commands as a Unix daemon


Daemonize
daemonize runs a command as a Unix daemon. As defined in W. Richard Stevens’ 1990 book, UNIX Network Programming (Addison-Wesley, 1990), a daemon is “a process that executes ‘in the background’ (i.e., without an associated terminal or login shell) either waiting for some event to occur, or waiting to perform some specified task on a periodic basis.” Upon startup, a typical daemon program will:

  • Close all open file descriptors (especially standard input, standard output and standard error)
    Change its working directory to the root filesystem, to ensure that it doesn’t tie up another filesystem and prevent it from being unmounted
  • Reset its umask value
  • Run in the background (i.e., fork)
  • Disassociate from its process group (usually a shell), to insulate itself from signals (such as HUP) sent to the process group
  • Ignore all terminal I/O signals
  • Disassociate from the control terminal (and take steps not to reacquire one)
  • Handle any SIGCLD signals

Download: daemonize

Example Usage
Code Snippet
  1. daemonize ./samplescript.sh
End of Code Snippet

By checking running processes on our system, we can see our script running as a daemon...
Code Snippet
  1. ps -ef | grep samplescript
End of Code Snippet

root 898 1 0 10:51 ? 00:00:00 /bin/sh /usr/local/bin/samplescript.sh

No comments: