Pergunta

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

Foi útil?

Solução

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.

Outras dicas

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();
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top