Thursday, September 24, 2015

Object Oriented Daemon implementation in Python3


1.What is a daemon?

A daemon is program that runs in the background and does some work. It does not need any user interaction to do its work.

Features of a daemon

  • It does not have access to the terminal, i.e. it cannot read or write to the terminal.
  • Only one instance of  it can be created.
  • It works without user interaction.
Example:  sshd is a daemon that services incoming SSH connections.

 2. My python daemon module:

The OO daemon module provided a simple implementation on a daemon which can be used as a base class to create daemon processes. All one needs to do to create a daemon using the daemon module as bellow.
  1. Import the daemon module
  2. Create a child class of the daemon
  3. Override the run method. This is were the business logic for your daemon goes. It should be implemented inside an infinite loop as shown in the example.
  4. Create and instance of the child daemon with daemon name and log directory path as parameters.
  5. Call the startDaemon method  the daemon.  

3. Example: Backup your clip board every 10 seconds.

Clipboard archiver daemon (clipboard_archiver_d.py)

4. Running the daemon

  $ yourdeamon.py [status|restart|stop]

$ ./clipboard_archiver_d2.py
clipcopy: started at 24.09.2015 / 22:22:58
clipcopy: log directory is '/tmp/clipcopy'
clipcopy: going into background........
$ ./clipboard_archiver_d2.py status
clipcopy:DAEMON_RUNNING
$ ./clipboard_archiver_d2.py restart
clipcopy:DAEMON_STOPPED
clipcopy: started at 24.09.2015 / 22:23:15
clipcopy: log directory is '/tmp/clipcopy'
clipcopy: going into background........
$ ./clipboard_archiver_d2.py stop
clipcopy:DAEMON_STOPPED

5. Daemon Module code


6. References