创建 python 循环作为 "detached" 子进程

Create python loop as a "detached" child process

我有一个潜在的无限 python 'while' 循环,即使在主 script/process 执行完成后我也想保持 运行。此外,如果需要的话,我希望以后能够从 unix CLI 中终止这个循环(即 kill -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

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

import os

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

Popen returns 具有 pid 的对象。根据 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.

您需要关闭 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))
        ...