Python: Create a daemon in Linux to empty log file every 10 seconds

This script will run a daemon and will clear any log mentioned in variable cmd1 every 10 seconds. Two things:

1. You need to install python-daemon to run this.

https://pypi.python.org/pypi/python-daemon/

2. It is not a simple python script, so you can't run it using ./mydaemon.py. You have to run it by using ./mydaemon.py start.

3. Again, you can't stop this script by "Ctrl + C" . You have to use ./mydaemon.py stop

4. Works with python 2.x

-------------------------------------------------------------------------------

#!/usr/bin/python
import time
import os
from daemon import runner

class App():
    def __init__(self):
        self.stdin_path = '/dev/null'
        self.stdout_path = '/dev/tty'
        self.stderr_path = '/dev/tty'
        self.pidfile_path =  '/tmp/foo.pid'
        self.pidfile_timeout = 5
    def run(self):
        while True:
            print "Going to clear log !! "
            cmd1 = 'cat /dev/null > /var/log/mysqld.log'
            os.system(cmd1)
            time.sleep(10)

app = App()
daemon_runner = runner.DaemonRunner(app)
daemon_runner.do_action()

Comments