簡體   English   中英

python子進程中的.kill()殺死父進程而不是子進程

[英].kill() in python subprocess kills parent rather than child process

我正在嘗試在下面的函數中打開第二個python腳本的子進程。 似乎可以很好地打開該進程,但是當我嘗試結束該進程時,父進程終止,子進程仍然存在。 關於為什么會發生這種情況的任何建議?

def thermostat(input):
global ThermostatRunning
global proc
print("Thermostat Function input: %s" % input)
if input == 'stop' and ThermostatRunning == 1:
    print("test")
    proc.kill()
    print proc.poll()
    dev2(0) #ensure heater is off
    return('Thermostat turned off')
elif input=='stop' and ThermostatRunning == 0:
    status = "Thermostat already stopped"
    print(status)
    return(status)
if input.isdigit() == 0:
        return("Thermostat input is not a number or -stop-")
if ThermostatRunning == 1:
    print("test2")
    proc.kill()
print("test3")
proc = subprocess.Popen('python thermostat.py -t %s' % input, shell=True)#, preexec_fn=os.setsid)
ThermostatRunning = 1
#for line in proc.stdout.readlines():
    #print (line)
status = "Thermostat started with set temperature: %s" % input
print(status)
return(status)

可能與此相關的唯一其他問題是這是一個燒瓶腳本。 我不確定這是否會改變。

當您使用shell = True創建子進程時,實際上是生成了一個生成另一個子進程的進程,因此,當您調用proc.kill()時,您只是在殺死父進程。 您想讓您的子流程成為流程組負責人,以便您可以一次殺死它們。

取消注釋Popen調用中的setid並殺死整個進程組,如下所示:

os.killpg(proc.pid, signal.SIGTERM)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM