开发者

"Trap" control-d and control-c

I have a console开发者_StackOverflow 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++?


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);
}


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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜