I'm trying to write a program in C (on Linux) that loops until the user presses a key, but shouldn't require a keypress to continue each loop.
Is there a simple way to do this? I figure I could possibly do it with select()
but that seems like a lot of work.
Alternatively, is there a way to catch a ctrl-c keypress to do cleanup before the program closes instead of non-blocking io?
On UNIX systems, you can use
sigaction
call to register a signal handler forSIGINT
signal which represents the Control+C key sequence. The signal handler can set a flag which will be checked in the loop making it to break appropriately.There is no portable way to do this, but select() might be a good way. See http://c-faq.com/osdep/readavail.html for more possible solutions.
The curses library can be used for this purpose. Of course,
select()
and signal handlers can be used too to a certain extent.Here's a function to do this for you. You need
termios.h
which comes with POSIX systems.Breaking this down:
tcgetattr
gets the current terminal information and stores it int
. Ifcmd
is 1, the local input flag int
is set to non-blocking input. Otherwise it is reset. Thentcsetattr
changes standard input tot
.If you don't reset standard input at the end of your program you will have problems in your shell.