Kill child process when parent process is killed

前端 未结 15 2693
轻奢々
轻奢々 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:57

    Yet another addition to the abundant richness of solutions proposed so far....

    The problem with many of them is that they rely upon the parent and child process to shut down in an orderly manner, which isn't always true when development is underway. I found that my child process was often being orphaned whenever I terminated the parent process in the debugger, which required me to kill the orphaned process(es) with Task Manager in order to rebuild my solution.

    The solution: Pass the parent process ID in on the commandline (or even less invasive, in the environment variables) of the child process.

    In the parent process, the process ID is available as:

    Process.CurrentProcess.Id;
    

    In the child process:

    Process parentProcess = Process.GetProcessById(parentProcessId);
    parentProcess.Exited += (s, e) =>
    {
        // clean up what you can.
        this.Dispose();
        // maybe log an error
        ....
    
        // And terminate with prejudice! 
        //(since something has already gone terribly wrong)
        Process.GetCurrentProcess().Kill();
    };
    

    I am of two minds as to whether this is acceptable practice in production code. On the one hand, this should never happen. But on the other hand, it may mean the difference between restarting a process, and rebooting a production server. And what should never happen often does.

    And it sure is useful while debugging orderly shutdown problems.

提交回复
热议问题