2017-07-13 211 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 –