![](/img/trans.png)
[英]python: Create a detached process and communicate with it via command line
[英]Create python loop as a “detached” child process
我有一個潛在的無限python'while'循環,即使在主腳本/流程執行完成后我也想繼續運行。 此外,我希望以后能夠在需要時從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
返回一個有pid
的對象。 根據文件
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))
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.