Killing external process when application dies

一个人想着一个人 提交于 2019-12-11 15:07: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();
}

回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/15206516/killing-external-process-when-application-dies

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!