How does one catch Ctrl+C in C?
相关问题
- Multiple sockets for clients to connect to
- What is the best way to do a search in a large fil
- glDrawElements only draws half a quad
- Index of single bit in long integer (in C) [duplic
- Equivalent of std::pair in C
Addendum regarding UN*X platforms.
According to the
signal(2)
man page on GNU/Linux, the behavior ofsignal
is not as portable as behavior ofsigaction
:On System V, system did not block delivery of further instances of the signal and delivery of a signal would reset the handler to the default one. In BSD the semantics changed.
The following variation of previous answer by Dirk Eddelbuettel uses
sigaction
instead ofsignal
:Or you can put the terminal in raw mode, like this:
Now it should be possible to read Ctrl+C keystrokes using
fgetc(stdin)
. Beware using this though because you can't Ctrl+Z, Ctrl+Q, Ctrl+S, etc. like normally any more either.The function sig_handler checks if the value of the argument passed is equal to the SIGINT, then the printf is executed.
Set up a trap (you can trap several signals with one handler):
Handle the signal however you want, but be aware of limitations and gotchas:
Regarding existing answers, note that signal handling is platform dependent. Win32 for example handles far fewer signals than POSIX operating systems; see here. While SIGINT is declared in signals.h on Win32, see the note in the documentation that explains that it will not do what you might expect.
Check here:
Note: Obviously, this is a simple example explaining just how to set up a CtrlC handler, but as always there are rules that need to be obeyed in order not to break something else. Please read the comments below.
The sample code from above: