试试这个代码。它运行一个 python 脚本作为守护进程:
import os
import time
from datetime import datetime
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 = '/var/run/mydaemon.pid'
self.pidfile_timeout = 5
def run(self):
filepath = '/tmp/mydaemon/currenttime.txt'
dirpath = os.path.dirname(filepath)
while True:
if not os.path.exists(dirpath) or not os.path.isdir(dirpath):
os.makedirs(dirpath)
f = open(filepath, 'w')
f.write(datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M:%S'))
f.close()
time.sleep(10)
app = App()
daemon_runner = runner.DaemonRunner(app)
daemon_runner.do_action()
用法:
> python mydaemon.py
usage: md.py start|stop|restart
> python mydaemon.py start
started with pid 8699
> python mydaemon.py stop
Terminating on signal 15