(in Linux)
The methods I found all use signal
.
Is there no other way? Is there anything I can do to make the terminal put it into the input buffer?
(in Linux)
The methods I found all use signal
.
Is there no other way? Is there anything I can do to make the terminal put it into the input buffer?
In order to "read CTL+C as input" instead of having it generate a SIGINT
it is necessary to use tcsetattr
() to either clear cc_c[VINTR]
or clear the ISIG
flag as described in the manual page that I linked to, here.
You will need to use tcgetattr
, first, to read the current terminal settings, adjust them accordingly, then tcsetattr
to set them.
You should make sure that the terminal settings get reset to their original defaults when your program terminates, it is not a given that the shell will reset them to default, for you.
Nope, signal()
is not the way. You should need to configure the tty
driver to do raw input (no input char processing in the driver), so it passes all characters untouched. But this requires considering the tty
input device as special and write special code to treat that case (this requires you to issue several ioctl
system calls). But this is not recommended, for the reasons explained below.
Second, there's another, simpler way that doesn't require to use raw mode. You can escape the Ctrl-C character by prepending the tty
escape character. In Linux and BSD system, this is normally tied to the Ctrl-V character, so pressing Ctrl-V + Ctrl-C allows you to input a single Ctrl-C char. I have just checked it with the hd
command:
$ hd
^C
00000000 : 03 0a : ..
00000002
$ _
Next question is, then, how to input a Ctrl-V? well, just double it! (but we are out of scope now, just continue reading)
The advantage of this approach is that it doesn't require programming in your program and will work the same way when reading from a file, pipe, fifo, socket, etc. (to which Ctrl-C has no special meaning, as the tty
driver is out of scene) The only device that generates an interrupt when detecting Ctrl-C is the tty
driver (more exactly, the controlling tty
, in it's code generic part, so all tty
s do this) and it also has a escape character (by the same reason, all tty
s have it) to invalidate the special meaning of the next character.
You can check which character is the escape character with the stty(1)
command, configured as the lnext
entry. But I can almost ensure you that it will be Ctrl-V.
This also applies to any other special character (like Ctrl-D, Ctrl-H, etc. that the terminal uses for special purposes)