如何判断一个ffmpeg子进程是否掉线

How to determine if a ffmpeg subprocess has fallen

我有一个问题

我想使用 subprocess.popen 创建一个新的 ffmpeg 进程 找出他的pid 并在 python 程序的主体中查看进程是否存在

args = shlex.split ('ffmpeg -i rtsp: //192.168.1.68: 8554 / mystream -f segment -strftime 1 -segment_time 5 13_REG1_CHANNEL3_% Y-% m-% d_% H-% M-% S-% s .mp3 ')
print (args)
proc = subprocess.Popen (args, stdout = subprocess.PIPE)
ch_pid = proc.pid
print (proc.pid)
proc.wait ()
print (proc.communicate ())
while (1):
 if (os.system (str ('kill -0 {PID}'). format (PID = ch_pid)) == 0):
   print ('proc is alive')
 else:
   break

在 while 循环中我试图通过 kill -0 pid 检查这个进程 pid 如果一切正常且进程为 运行

,此命令将 return 归零

但是

如果ffmpeg会掉 不会有任何变化

kill -0 pid 将继续returning 零代码表明一切正常

我该怎么办?

您可以使用 proc.poll() 来解决它。
参见:

这是一个例子:

import shlex
import subprocess

#args = shlex.split ('ffmpeg -i rtsp: //192.168.1.68: 8554 / mystream -f segment -strftime 1 -segment_time 5 13_REG1_CHANNEL3_% Y-% m-% d_% H-% M-% S-% s .mp3 ')
args = shlex.split ('ffmpeg -i rtsp://wowzaec2demo.streamlock.net/vod/mp4:BigBuckBunny_115k.mov -vcodec copy -acodec copy BigBuckBunny_115k.mov')

print (args)
proc = subprocess.Popen (args, stdout = subprocess.PIPE)
ch_pid = proc.pid
print (proc.pid)
proc.wait ()
print (proc.communicate ())
while (1):
    poll = proc.poll()
    if poll is None:
        print ('proc is alive')
        # p.subprocess is alive
    else:
        print ('proc is dead')
        break

这是一个更简洁的代码示例:

import shlex
import subprocess
import time

args = shlex.split ('ffmpeg -y -i rtsp://wowzaec2demo.streamlock.net/vod/mp4:BigBuckBunny_115k.mov -vcodec copy -acodec copy BigBuckBunny_115k.mov')

proc = subprocess.Popen(args)

while True:
    poll = proc.poll()
    if poll is None:
        print ('proc is alive')
    else:
        print ('proc is dead')
        break
    time.sleep(1)

proc.wait()