views:

1399

answers:

7

How do I catch a ctrl-c event in C++?

+5  A: 

You have to catch the SIGINT signal (we are talking POSIX right?)

See @Gab Royer´s answer for sigaction.

Example:

#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;

}
Tom
Yes, it's POSIX. I forgot to add Linux to the question.
Scott
signal() behaves differently, depending if it follows BSD or SysV style. sigaction() is preferable.
asveikau
A: 

IMHO it's platform dependent.

Dmitriy
That's not an opinion, that's fact :)
Tony k
+13  A: 

signal isn't the most reliable way as it differs in implementations. I would recommend using sigaction. Tom's code would now look like this :

#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)
{

   struct sigaction sigIntHandler;

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

   sigaction(SIGINT, &sigIntHandler, NULL);

   while(1);
   return 0;

}
Gab Royer
I would just like to say thanks for asking this question, as I have an exam on the matter tomorow morning :)
Gab Royer
I think my_handler should take `int s` as it's argument. `sig_t` is itself a function pointer type.
Matthew Marshall
<stdlib.h>, etc - it's C, not C++. In C++ you should use <cstdlib>
Abyx
A: 

Yeah, this is a platform dependent question.

If you are writing a console program on POSIX, use the signal API (#include <signal.h>).

In a WIN32 GUI application you should handle the WM_KEYDOWN message.

Joyer
+4  A: 

For a Windows console app, you want to use SetConsoleCtrlHandler to handle CTRL+C and CTRL+BREAK.

See here for an example.

Chris Smith
A: 

For whatever it's worth, here's how I did it in my program:

  QChar chr(getch());
  if(chr == 3)
  {
    emit sigCtrlC();
  }

I tested it, and it works.

ShaChris23
A: 

Can anybody help me? how can I do catch a CTRL+X event. CTRL+X should terminate (kill) all tasks except task 0 (shell) <<-- it's my homework(((. thanks

Bekzat