繁体   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