创建python循环作为“分离的”子进程

时间:2019-04-19 20:20:12

标签: python infinite-loop

我有一个潜在的无限python'while'循环,即使主脚本/进程执行完成后,我也希望继续运行。此外,我希望以后能够根据需要从UNIX CLI终止此循环(即,杀死-SIGTERM PID),因此也需要循环的pid。我将如何完成?谢谢!

循环:

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 个答案:

答案 0 :(得分:0)

在python中,父进程尝试退出时退出其所有守护进程子进程。但是,您可以使用os.fork()创建一个全新的过程:

import os

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

答案 1 :(得分:0)

Popen返回具有pid的对象。根据{{​​3}}

  

Popen.pid   子进程的进程ID。

     

请注意,如果将shell参数设置为True,则这是生成的shell的进程ID。

您需要关闭shell=True以获得进程的pid,否则它将给出shell的pid。

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))
        ...