C # prevents ctrl-c for child processes

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

When Ctrl + C (SIGINT) is issued to the console, the host must safely terminate other processes. The problem is that other processes also receive Ctrl + C and terminate immediately before the host can safely disable them.

I know that Ctrl + C is issued to every process in the console process tree. What can I do to prevent Ctrl + C from being pressed on these other processes if the host is still up and running? I am not involved in the development of other processes and therefore cannot directly modify their processing Ctrl + C. Thanks

+4
source share
2 answers

Apparently, you can install Console.TreatCtrlCAsInput = trueone that will allow you to handle this keystroke, stop other processes, and then lose your temper. According to MSDN docs, this property ...

Gets or sets a value indicating whether the combination of the Control modifier key and the console key C (Ctrl + C) will be considered as a normal input or as an interrupt processed by the operating system.

+4
source

To clarify the answer marked as correct.

Console.TreatCtrlCAsInput SIGINT , C , .

:

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();
}
+1

All Articles