簡體   English   中英

Python殺死一個子進程(啟動另一個進程)並再次啟動它

[英]Python kill a subprocess(that starts another process) and start it again

我正在嘗試制作一個Python腳本,以啟動程序livestreamer(啟動程序mplayer),並在10秒鍾后將其殺死該程序或子進程。 這是我當前的無效代碼,我想我知道為什么,但是我不知道如何解決。 我認為問題在於子進程啟動了livestreamer,然后程序livestreamer啟動了程序mplayer。 Python不了解mplayer,因此無法將其關閉。 如何在10秒后殺死livestreamer和mplayer,然后重新啟動它們? 我正在使用Ubuntu 14.04(Linux)和Python 2.7.6

import subprocess
import time
import os
import sys
import signal

url = "http://new.livestream.com/accounts/398160/events/3155348"
home = os.environ['HOME']

if not os.geteuid() == 0:
    if not os.path.exists('/%s/.config/livestreamer' % home):
        os.makedirs('/%s/.config/livestreamer' % home)
    lscfg = open('%s/.config/livestreamer/config' % home, 'w+')
    lscfg.write("player=mplayer -geometry 0%:0% -nomouseinput -loop 100 -noborder -fixed-vo")
    lscfg.close()

cmd = "livestreamer %s best --player-continuous-http --player-no-close" % url
while True:
    proc1 = subprocess.Popen(cmd.split(), shell=False)
    time.sleep(10)
    proc1.kill()

解:

import subprocess
import time
import os
import sys
import signal

url = "http://new.livestream.com/accounts/398160/events/3155348"
home = os.environ['HOME']

if not os.geteuid() == 0:
    if not os.path.exists('/%s/.config/livestreamer' % home):
        os.makedirs('/%s/.config/livestreamer' % home)
    lscfg = open('%s/.config/livestreamer/config' % home, 'w+')
    lscfg.write("player=mplayer -geometry 0%:0% -nomouseinput -loop 100 -noborder -fixed-vo")
    lscfg.close()
cmd = "livestreamer %s best --player-continuous-http --player-no-close" % url
#restarting the player every 10th minute to catch up on possible delay
while True:
    proc1 = subprocess.Popen(cmd.split(), shell=False)
    time.sleep(600)
    os.system("killall -9 mplayer")
    proc1.kill()

如您所見,os.system(“ killall -9 mplayer”)是殺死進程mplayer的命令。

在您的代碼中,您殺死了livestreamer,但沒有殺死mplayer,因此mplayer將繼續運行。

通過在子進程上使用kill命令,您將發送信號SIGKILL,除非子進程確實處理了信號中斷,否則它只會快速關閉自身並且不會殺死自己的孩子,因此mplayer將會存活(並且可能會成為僵屍進程)。

您沒有引用子進程孩子“ mplayer”,但如果可以獲取其PID,則可以使用os.kill(...)將其殺死

os.kill(process_pid, signal.SIGTERM)

使用os.system("killall -9 mplayer")是解決此問題的簡便方法。 使用此選項的想法會殺死mplayer的所有進程,盡管在我看來這不是問題,但在其他情況下可能是問題。

while True:
        proc1 = subprocess.Popen(cmd.split(), shell=False)
        time.sleep(600)
        os.system("killall -9 mplayer")
        proc1.kill()

暫無
暫無

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

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