Kill child process when parent process is killed

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

    I was looking for a solution to this problem that did not require unmanaged code. I was also not able to use standard input/output redirection because it was a Windows Forms application.

    My solution was to create a named pipe in the parent process and then connect the child process to the same pipe. If the parent process exits then the pipe becomes broken and the child can detect this.

    Below is an example using two console applications:

    Parent

    private const string PipeName = "471450d6-70db-49dc-94af-09d3f3eba529";
    
    public static void Main(string[] args)
    {
        Console.WriteLine("Main program running");
    
        using (NamedPipeServerStream pipe = new NamedPipeServerStream(PipeName, PipeDirection.Out))
        {
            Process.Start("child.exe");
    
            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }
    }
    

    Child

    private const string PipeName = "471450d6-70db-49dc-94af-09d3f3eba529"; // same as parent
    
    public static void Main(string[] args)
    {
        Console.WriteLine("Child process running");
    
        using (NamedPipeClientStream pipe = new NamedPipeClientStream(".", PipeName, PipeDirection.In))
        {
            pipe.Connect();
            pipe.BeginRead(new byte[1], 0, 1, PipeBrokenCallback, pipe);
    
            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }
    }
    
    private static void PipeBrokenCallback(IAsyncResult ar)
    {
        // the pipe was closed (parent process died), so exit the child process too
    
        try
        {
            NamedPipeClientStream pipe = (NamedPipeClientStream)ar.AsyncState;
            pipe.EndRead(ar);
        }
        catch (IOException) { }
    
        Environment.Exit(1);
    }
    

提交回复
热议问题