Kill FFmpeg process smoothly

by GarciaPL on Thursday 3 April 2014

Let's assume that you use FFmpeg distribution in your application. One of your function is for instance saving some HLS stream (HTTP Live Streaming) into file. I suppose you are using python subprocess module to create process in Linux OS to obtain this stream to your hard disk.

In normal way if you would like to stop saving this content using FFmpeg on your storage, you will just press 'q' button while you are in terminal. Due to this FFmpeg will be able to finish saving content and do not damage the file at the end.

There is some kind of problem if you would like to kill this FFmpeg process in smooth way without damaging the file while you do not have access to the terminal.

You can use below solution written in Python to kill this FFmpeg process from your application. Only input which you need to ensure is PID (Process IDentifier) which describes your  process. You can use below shell code in Linux :

ps -ef | grep ffmpeg | awk '{print $2}'

Once you know PID of your FFmpeg process just use this Python code :
import psutil
import os
import signal

pids = psutil.get_pid_list()

for pid in pids:
      if (pid == <your_PID>):
            os.kill(pid,signal.SIGINT)
One thing is worthy of attention. You suppose to use mainly signal.SIGINT while you invoke os.kill function, because of it simulates in FFmpeg case the user interrupt of this process (typically initiated by pressing Control-C) which allow to FFmpeg to end his work properly.

Reference : [1] Python.org Subprocess Docs [2] Thelightfromtheblackhole.blogspot.com Sending sighup signal to some external [3] Unix signal - SIGINT