0

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
user1998671
  • 125
  • 1
  • 6
  • Possible duplicate: https://stackoverflow.com/questions/473620/how-do-you-create-a-daemon-in-python – rdas Apr 19 '19 at 20:22

2 Answers2

1

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!")
A.J. Uppal
  • 19,117
  • 6
  • 45
  • 76
0

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))
        ...
lange
  • 590
  • 5
  • 9