Killing external process when application dies

2019-08-29 13:28发布

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();
}

2条回答
Bombasti
2楼-- · 2019-08-29 13:54

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

查看更多
老娘就宠你
3楼-- · 2019-08-29 14:14

There is nothing you can do when your process is terminated. There is no code run in your process after someone kills it with TerminateProcess call.

In case of more graceful cases (i.e. unhandled exception) you may have global handler that does something close to what you want.

查看更多
登录 后发表回答