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

2 Answers

0
A.J. Uppal On Best Solutions

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!")
0
lange On

Popen returns an object which has the pid. According to the doc

Popen.pid The process ID of the child process.

Note that if you set the shell argument to True, this is the process ID of the spawned shell.

You would need to turnoff the shell=True to get the pid of the process, otherwise it gives the pid of the shell.

args = 'ping -c 1 1.2.3.4'

while True:
    time.sleep(60)
    with subprocess.Popen(args, shell=False, stdout=subprocess.PIPE) as proc:
        print('PID: {}'.format(proc.pid))
        ...