How to make a python program run as daemon

To make a python program run as daemon process use the following program..

#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
#       Copyright 2013 ganesh #ganeshredcobra@gmail.com#
#
#       This program is free software; you can redistribute it and/or modify
#       it under the terms of the GNU General Public License as published by
#       the Free Software Foundation; either version 2 of the License, or
#       (at your option) any later version.
#
#       This program is distributed in the hope that it will be useful,
#       but WITHOUT ANY WARRANTY; without even the implied warranty of
#       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#       GNU General Public License for more details.
#
#       You should have received a copy of the GNU General Public License
#       along with this program; if not, write to the Free Software
#       Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#       MA 02110-1301, USA.

from os import fork, chdir, setsid, umask
from sys import exit
import serial,os
import time
import syslog


def main():
    port = "/dev/ttyUSB0"
    ser = serial.Serial(port, 9600, timeout=0)
    last_received = ''
    buffer = ''
    while 1:
        #main daemon process loop
        

# Dual fork hack to make process run as a daemon
if __name__ == "__main__":
      try:
        pid = fork()
        if pid > 0:
          exit(0)
      except OSError, e:
        exit(1)

      chdir("/")
      setsid()
      umask(0)

      try:
        pid = fork()
        if pid > 0:
          exit(0)
      except OSError, e:
        exit(1)
main()
Put the program you want to daemonize inside the main function…now just run the program the process in main function will become daemon process..
to test the above program modify main function like this
def main():
     syslog.syslog('event occured')
     time.sleep(10)
Now run the program it becomes daemon and to check that
sudo tail -f  /var/log/syslog
you can see it will print “event occured” every ten seconds…
Happy hacking 🙂
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s