Search code examples
c#processunmanagedresources

Killing external process when application dies


I've been working on a small piece that calls an external executable (ffmpeg in my case) And then I wrote a test and used test runner in a debug mode, now if I stop debugging (terminate) it still runs ffmpeg. I tried to kill the process in the finalizer and with IDisposable - it still runs. How can I make sure that the process never will be left like that, and if the caller dies or fails or gets stopped by any means, the ffmpeg executable guaranteed to be killed.

I run the process as usual (nothing fancy)

var processInfo = new ProcessStartInfo(ffmpegPath)
{
    UseShellExecute = false,
    Arguments = arguments,
    RedirectStandardOutput = true,
    RedirectStandardError = true,
    CreateNoWindow = true,
};

using (var ffmpegProc = new Process())
{
    ffmpegProc.EnableRaisingEvents = true;
    ffmpegProc.StartInfo = processInfo;
    ffmpegProc.Start();
    ffmpegProc.WaitForExit();
}

Solution

  • You should use JobObject

    With JobObject you can add child processes. So if the main process is killed or closed the os will terminate all child processes.

    source: http://www.xtremevbtalk.com/showpost.php?p=1335552&postcount=22

    Another solution is to pass to child object the parent PID.

    Any child have to check for parent PID existence and if not found kill itself