¿Cómo puedo capturar un evento ctrl-c? (C++)


¿Cómo puedo coger un Ctrl+C evento en C++?

Author: Bugfinger, 2009-10-29

4 answers

signal no es la forma más confiable, ya que difiere en implementaciones. Yo recomendaría usar sigaction. El código de Tom ahora se vería así:

#include <signal.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>

void my_handler(int s){
           printf("Caught signal %d\n",s);
           exit(1); 

}

int main(int argc,char** argv)
{

   struct sigaction sigIntHandler;

   sigIntHandler.sa_handler = my_handler;
   sigemptyset(&sigIntHandler.sa_mask);
   sigIntHandler.sa_flags = 0;

   sigaction(SIGINT, &sigIntHandler, NULL);

   pause();

   return 0;    
}
 142
Author: Gab Royer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-02-28 11:28:54

Para una consola de Windows de la aplicación, usted desea utilizar SetConsoleCtrlHandler para manejar CTRL+C y CTRL+ROMPER.

Vea aquí para un ejemplo.

 44
Author: Chris Smith,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-25 00:22:50

Tienes que coger la señal SIGINT (estamos hablando de POSIX correcto?)

Ver la respuesta de @Gab Royers para sigaction.

Ejemplo:

#include <signal.h>
#include <stdlib.h>
#include <stdio.h>

void my_handler(sig_t s){
           printf("Caught signal %d\n",s);
           exit(1); 

}

int main(int argc,char** argv)
{
   signal (SIGINT,my_handler);

   while(1);
   return 0;

}
 26
Author: Tom,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-10-29 02:16:14

Sí, esta es una pregunta dependiente de la plataforma.

Si está escribiendo un programa de consola en POSIX, utilice la API de señal (#include ).

En una aplicación GUI WIN32 deberías manejar el mensaje WM_KEYDOWN.

 1
Author: Joyer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-06-19 00:14:54