tags:

views:

294

answers:

4

I have a console program and I want if the user press ctrl-z the program exits and if he press ctrl-c nothing happens. In Bash i'd put a trap, what I should use in C++?

+4  A: 

In Unix use signal() in <signal.h> to register a function to invoke upon receiving a signal.

For example:

#include <signal.h>

void leave(int sig);

// ...
{
    signal(SIGINT,leave);
    for(;;) getchar();
}

// Beware:  calling library fn from signal handler isn't std-conforming
//          and may not work.
void leave(int sig)
{
    exit(sig);
}
wilhelmtell
You should be calling `_Exit(sig)` instead of `exit(sig)` here. The former is safe within signal handlers the latter is not.
D.Shawley
`signal()` behaves differently on different platforms. `sigaction()` is slightly more complicated, but is portable.
Bastien Léonard
+1  A: 

For the Ctrl + C you have to catch SIGINT signal. Look here.

Kugel
+1  A: 

That's platform specific, of course. C++ itself has no knowledge of keyboard input or signal handling.

As you mentioned bash, I guess you are on Linux or some kind of UN*X. In this case, take a look at signal.h.

mkluwe
The C and C++ standards both have a lot to say about signal handling and keyboard input. Neither have much to say about process suspension though but `SIGINT` and `signal()` are both covered.
D.Shawley
I don't think the C or C++ language assumed that there even is a keyboard. But you're right, both `SIGINT` and `signal()` are part of the C standard header `signal.h`, meaning you can set signal handling functions and raise signals.
mkluwe
+2  A: 

If you are using a UNIX based system, then you want either signal() or sigaction() depending on your preference and threading model; personally, I would recommend sigaction() over signal(). You want to trap SIGTSTP and SIGINT. Read the Signal Concepts section of the Single UNIX Specification for a good description of how to use them.

If you have some spare time, read the W. Richard Steven's classic Advanced Programming in the UNIX Environment. You will never be sorry. If you expect to be doing more UNIX system's programming tasks, then pick up copies of POSIX Programmers Guide and POSIX.4 Programmers Guide as well. They serve as great introductions and references.

D.Shawley