应用程序终止后终止外部进程 [英] Killing external process when application dies

查看:139
本文介绍了应用程序终止后终止外部进程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在研究一个小的文件,该文件调用外部可执行文件(在我的情况下为ffmpeg) 然后我编写了一个测试,并在调试模式下使用了测试运行器,现在,如果我停止调试(终止),它仍然会运行ffmpeg.我试图在终结器中使用IDisposable终止该进程-该进程仍在运行.我该如何确保该进程永远不会像这样留下来,并且如果调用者死亡,失败或以任何方式被停止,则ffmpeg可执行文件一定会被杀死.

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

推荐答案

您应使用使用JobObject可以添加子进程.因此,如果主进程被终止或关闭,则操作系统将终止所有子进程.

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

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

另一种解决方案是将父PID传递给子对象.

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

任何孩子都必须检查父PID的存在,如果找不到,则会杀死自己

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

这篇关于应用程序终止后终止外部进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆