简体   繁体   English

当应用程序进程被杀死/崩溃时,杀死子进程

[英]Kill child process when application process is killed/crashed

I'm creating new processes from my application and want these processes to be killed when/if my application is crashed. 我正在从我的应用程序创建新进程,并希望在/如果我的应用程序崩溃时将这些进程杀死。

So i found this post: Kill child process when parent process is killed . 所以我发现了这篇文章: 当父进程被杀死时,杀死子进程 I took the first example and copied all the code to a new class under a function public void Close() . 我以第一个示例为例,并将所有代码复制到public void Close()函数下的新类中。

Got an error - The name Win32 does not exist in the current context so I added Microsoft.Win32 and now another error - CloseHandle is not recognized. 出现错误-当前上下文中不存在Win32名称,因此我添加了Microsoft.Win32 ,现在又出现了另一个错误-无法识别CloseHandle

The type or namespace name 'CloseHandle' does not exist in the namespace 'Microsoft.Win32' (are you missing an assembly reference? ) 类型或名称空间名称'CloseHandle'在名称空间'Microsoft.Win32'中不存在(您是否缺少程序集引用?

How can i fix it ? 我该如何解决?

a simpler approach- or so i believe 一种更简单的方法-或我相信

keep track of all the processes u start. 跟踪您启动的所有过程。

ArrayList chilProcess_id = new ArrayList();

    public void process_starter()
    {            
        Process p;
        p = new System.Diagnostics.Process();           
        p.StartInfo.FileName = "YOUR PROCESS PATH";
        if (!p.Start())
             chilProcess_id.Add(p.Id);
    }

Now before exiting, kill those processes. 现在,退出之前,请终止这些进程。

public void exitApplication()
    {
        Process p;
        foreach (int p_id in chilProcess_id)
        {
            p = Process.GetProcessById(p_id);
            try
            {
                if(!p.HasExited)
                    p.Kill();
            }
            catch (Exception e)
            {
                //Handle the exception as you wish
            }
        }
    }

for ArrayList add namespace 为ArrayList添加名称空间

using System.Collections;

for Process add namespace 用于流程添加名称空间

using System.Diagnostics;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM