3

I have a main thread of a Console Application that runs few external processes this way

    private static MyExternalProcess p1;
    private static MyExternalProcess p2;
    private static MyExternalProcess p3;

    public void Main() {
        p1 = new MyExternalProcess();
        p2 = new MyExternalProcess();
        p3 = new MyExternalProcess();

        p1.startProcess();
        p2.startProcess();
        p3.startProcess();
    }

    public static void killEveryoneOnExit() {
        p1.kill();
        p2.kill();
        p3.kill();
    }


    class MyExternalProcess {
      private Process p;
      ...
      public void startProces() {
             // do some stuff
             PlayerProcess = new Process();
             ....
             PlayerProcess.Start();
             // do some stuff
      }

      public void kill() {
             // do some stuff
             p.Kill();
      }
    }          

What I need to do is: when the Main thread is interrupted (exit button or ctrl+c), the other processes should be killed. How do I trigger my method killEveryoneOnExit on CTRL+C or Exit (X) button?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Manu
  • 4,019
  • 8
  • 50
  • 94
  • 1
    Duplicate: Look at http://stackoverflow.com/questions/3342941/kill-child-process-when-parent-process-is-killed for the correct way to set your child processes or at http://stackoverflow.com/questions/177856/how-do-i-trap-ctrl-c-in-a-c-sharp-console-app if you want to handle Ctrl-C yourself anyway. – Eli Algranti Nov 03 '13 at 22:12
  • I have edited your title. Please see, "[Should questions include “tags” in their titles?](http://meta.stackexchange.com/questions/19190/)", where the consensus is "no, they should not". – John Saunders Nov 03 '13 at 23:42

1 Answers1

7

Based on your question there are two events you need to catch.

If you put these two together with your example you get something like this:

static ConsoleEventDelegate handler;
private delegate bool ConsoleEventDelegate(int eventType);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool SetConsoleCtrlHandler(ConsoleEventDelegate callback, bool add);

private static MyExternalProcess p1;

public static void Main()
{
    Console.CancelKeyPress += delegate
    {
        killEveryoneOnExit();
    };

    handler = new ConsoleEventDelegate(ConsoleEventCallback);
    SetConsoleCtrlHandler(handler, true);

    p1 = new MyExternalProcess();
    p1.startProcess();
}

public static void killEveryoneOnExit()
{
    p1.kill();
}

static bool ConsoleEventCallback(int eventType)
{
    if (eventType == 2)
    {
        killEveryoneOnExit();
    }
    return false;
}

For a working ctrl c (fun intended) paste example: http://pastebin.com/6VV4JKPY

Community
  • 1
  • 1
Jos Vinke
  • 2,704
  • 3
  • 26
  • 45