Kill child process when parent process is killed

前端 未结 15 2641
轻奢々
轻奢々 2020-11-22 05:59

I\'m creating new processes using System.Diagnostics.Process class from my application.

I want this processes to be killed when/if my application has cr

15条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-22 06:47

    I had the same problem. I was creating child processes that never got killed if my main app crashed. I had to destroy manually child processes when debugging. I found that there was no need to make the children somewhat depend on parent. In my main, I added a try catch to do a CleanUp() of child processes on exit.

        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            try
            {
                Application.Run(new frmMonitorSensors());
            }
            catch(Exception ex)
            {
                CleanUp();
                ErrorLogging.Add(ex.ToString());
            }
        }
    
        static private void CleanUp()
        {
            List processesToKill = new List() { "Process1", "Process2" };
            foreach (string toKill in processesToKill)
            {
                Process[] processes = Process.GetProcessesByName(toKill);
                foreach (Process p in processes)
                {
                    p.Kill();
                }
            }
        }
    

提交回复
热议问题