5

I have a console application (lets call it the host) that manages several applications using System.Diagnostics.Process. The host controls the starting and stopping of these external processes.

When Ctrl+C (SIGINT) is issued to the console the host should safely terminate the other processes. The problem is that the other processes also receive Ctrl+C and terminate immediately, prior to the host being able to shut them down safely.

I know that the Ctrl+C is issued to every process in the console process tree. What can I do to prevent the Ctrl+C from reaching these other processes if the host is still up and running? I am not involved in the development of the other processes, and so can not change their handling of Ctrl+C directly. Thanks

denver
  • 2,863
  • 2
  • 31
  • 45

2 Answers2

4

Apparently you can set Console.TreatCtrlCAsInput = true which will allow you to handle that keystroke, stop the other processes, and then exit yourself. According to the MSDN docs, this property...

Gets or sets a value indicating whether the combination of the Control modifier key and C console key (Ctrl+C) is treated as ordinary input or as an interruption that is handled by the operating system.

Community
  • 1
  • 1
Jeff B
  • 8,572
  • 17
  • 61
  • 140
  • I wonder if there's a Win32API type thing you could tie into to handle this. To me that'd seem a bit more ideal/more powerful... – Jeff B Nov 01 '13 at 15:02
1

To elaborate on the answer marked as correct.

Setting Console.TreatCtrlCAsInput will prevent the SIGINT signal from hitting all processes in the console process tree and instead result in the C key with a control modifier being sent to the application running in the terminal.

In code this looks like:

static void Main(string[] args)
{
    System.Console.TreatControlCAsInput = true;

    // start the server
    Server server = new Server();
    server.Start();

    // wait for Ctrl+C to terminate
    Console.WriteLine("Press Ctrl+C To Terminate");
    ConsoleKeyInfo cki;
    do
    {
        cki = Console.ReadKey();
    } while (((cki.Modifiers & ConsoleModifiers.Control) == 0) || (cki.Key != ConsoleKey.C));

    // stop the server
    server.Stop();
}
denver
  • 2,863
  • 2
  • 31
  • 45