Search code examples
pythoninfinite-loop

Create python loop as a "detached" child process


I have an potentially infinite python 'while' loop that I would like to keep running even after the main script/process execution has been completed. Furthermore, I would like to be able to later kill this loop from a unix CLI if needed (ie. kill -SIGTERM PID), so will need the pid of the loop as well. How would I accomplish this? Thanks!

Loop:

args = 'ping -c 1 1.2.3.4'

while True:
    time.sleep(60)
    return_code = subprocess.Popen(args, shell=True, stdout=subprocess.PIPE)
    if return_code == 0:
        break

Solution

  • In python, parent processes attempt to kill all their daemonic child processes when they exit. However, you can use os.fork() to create a completely new process:

    import os
    
    pid = os.fork()
    if pid:
       #parent
       print("Parent!")
    else:
       #child
       print("Child!")