Random thoughts shooting out of volatile mind
Creating a Daemon Process in Python
Daemons in computer world refers to a process that runs in background in a Unix like operating system you can read more on Daemons in this Wikipedia article. I knew how to create a daemon in the C program but didn't find any good article on how to do it in Python except this one. The main guidelines for writing a daemon process are as follows
  1. First the program needs to fork and parent should exit leaving the child as orphan which will be then adopted by the init process which is parent of all process in Unix like operating system. Caution: do take care so that your process doesn't end up as a Zombie Process (avoided by doing a double fork. 1st parent forks a child which then forks a second child after forking first child exits and then parent exits and the second child continues to execute as a daemon)
  2. A process has a controlling terminal and receives all signal from the terminal. Child inherits the terminal of process but a daemon should not receive any signal from controlling terminal so we need to disassociate from any terminal and also from process groups. This can be done by creating its own process group and becoming the session leader. To achieve this setsid system call is used
  3. By default a child process also inherits open file descriptor from its parent and most of the time it may not be using these resources so its good if we release/close all these file descriptors.
  4. Next is setting the working directory as / (root) this is done so that process doesn't keep any directory in use on a mounted file system (not allowing to unmount). But using / may not be good in all cases so working directory should be chosen carefully. This can be achived using chdir system call
  5. Setting the file creation mask is next step. Normally daemons will be running as super user and files created by it needs to be protected. This can be done by using umask system call.
  6. Catching the Signals is the next step. Normally daemon process may get signal from a user or other process. For eg a child process may send SIGCHLD when it terminates. Daemons should catch these signals and act accordingly (except SIGKILL). This can be done using signal handlers utilizing signal.h
  7. Daemon process won't be attached to any terminals or consoles so messages from daemon process needs to be written to some file or we need to use syslogd interface to log the events which is more flexible.
Well that’s about the steps / guide lines to create a daemon processes. Here is the code which I wrote in Python which uses double forking and creates a simple daemon which actually does nothing :P.
Posted by: copyninja on Sunday, 11 July 2010

blog comments powered by Disqus
Fork me on GitHub