2017-07-13 207 views
0

我期待构建一个守护进程,在给定一些输入时完成一些任务。 99%的时间它在背景上默默无闻,任务短而且数量少。我将如何构建两个应用程序之间的接口,其中一个应用程序构造任务和执行它的守护程序?守护进程结构

我在想守护进程可能有一个我定期检查的文件夹。如果里面有一些文件,它会读取它并遵循那里的指示。

这样工作还是会有更好的方法吗?

编辑:添加示例守护程序代码。

#!/usr/bin/python 

import time 
from daemon import runner 

class Daemon(): 
    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 

     self.task_dir = os.path.expanduser("~/.todo/daemon_tasks/") 

    def run(self): 
     while not time.sleep(1): 

      if len(os.listdir(self.task_dir)) == 0: 
       for task in os.listdir(self.task_dir): 
        self.process_task(task) 

    def process_task(self, task): 
     # input: filename 
     # output: void 

     # takes task and executes it according to instructions in the file 
     pass 



if __name__ == '__main__': 
    app = Daemon() 
    daemon_runner = runner.DaemonRunner(app) 
    daemon_runner.do_action() 

回答

1

我会研究FIFO的unix套接字作为选项。这消除了轮询某个目录的需要。一些SO链接帮助How to create special files of type socket?

+1

为了完整性的实现可以在这里找到:https://gist.github.com/Jonksar/10d20fd6274f40ee9023e09c742f8951 –