I am developing an application that uses C++ and compiles using Linux GNU C Compiler. However, I want to invoke a function as the user interrupts the script using CtrlC keys. What should I do? Any answers would be much appreciated.
相关问题
- Sorting 3 numbers without branching [closed]
- Multiple sockets for clients to connect to
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
Typing CtrlC normally causes the shell to send
SIGINT
to your program. Add a handler for that signal (viasignal(2)
orsigaction(2)
), and you can do what you like when CtrlC is pressed.Alternately, if you only care about doing cleanup before your program exits, setting up an exit handler via
atexit(3)
might be more appropriate.When you press Ctr + C, the operating system sends a signal to the process. There are many signals and one of them is SIGINT. The SIGINT ("program interrupt") is one of the Termination Signals.
There are a few more kinds of Termination Signals, but the interesting thing about SIGINT is that it can be handled (caught) by your program. The default action of SIGINT is program termination. That is, if your program doesn't specifically handle this signal, when you press Ctr + C your program terminates as the default action.
To change the default action of a signal you have to register the signal to be caught. To register a signal in a C program (at least under POSIX systems) there are two functions
These functions require the header signal.h to be included in your C code. I have provide a simple example of the
signal
function below with comments.Note: you should only call safe/authorized functions in signal handler. For example avoid calling printf in signal handler.
You can compile this code with gcc and execute it from the shell. There is an infinite loop in the code and it will run until you send a
SIGINT
signal by pressing Ctr + C.You can use the signal macro.
Here is an example of how to deal with it:
Sample output: