To make a python program run as daemon process use the following program..
#! /usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2013 ganesh #email@example.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 🙂