Search code examples
pythonmultiprocessingdaemon

How to implement a daemon process in Python?


I am writing a small program which has a heartbeat process and an echo process. I implemented this with a multiprocessing library, but it doesn't seem to work.

from multiprocessing import Process
import os
import time

def ticking():
    while True:
        time.sleep(1)
        print 'ticking'

def echo():
    while True:
        a = raw_input('please type something')
        print 'echo: ' + a

if __name__ == '__main__':
    p = Process(target=ticking, args=())
    p.start()
    p.join()

    p = Process(target=echo, args=())
    p.start()
    p.join()

Solution

  • You create a process that will run forever and join() to it. The second process will never get created, because the join() will stall your main process forever.

    If this is how you want to proceed, then you should for example first create both processes and then join them:

    if __name__ == '__main__':
        p1 = Process(target=ticking, args=())
        p1.start()
    
        p2 = Process(target=echo, args=())
        p2.start()
    
        p1.join()
        p2.join()