Non-blocking getch(), ncurses
Solution 1
The curses library is a package deal. You can't just pull out one routine and hope for the best without properly initializing the library. Here's a code that correctly blocks on getch()
:
#include <curses.h>
int main(void) {
initscr();
timeout(-1);
int c = getch();
endwin();
printf ("%d %c\n", c, c);
return 0;
}
Solution 2
From a man page (emphasis added):
The
timeout
andwtimeout
routines set blocking or non-blocking read for a given window. Ifdelay
is negative, blocking read is used (i.e., waits indefinitely for input).
Solution 3
You need to call initscr()
or newterm()
to initialize curses before it will work. This works fine for me:
#include <ncurses.h>
int main() {
WINDOW *w;
char c;
w = initscr();
timeout(3000);
c = getch();
endwin();
printf("received %c (%d)\n", c, (int) c);
}
Mars
Python haxxorz and parapsychology student. Creator of the eminent finplot library: https://github.com/highfestiva/finplot. Once upon a time made a UFO short documentary in Swedish: https://www.youtube.com/watch?v=HFF528pc3O8. Constantly at a fork in the road.
Updated on May 25, 2020Comments
-
Mars about 4 years
I'm having some problems getting ncurses' getch() to block. Default operation seems to be non-blocking (or have I missed some initialization)? I would like it to work like getch() in Windows. I have tried various versions of
timeout(3000000); nocbreak(); cbreak(); noraw(); etc...
(not all at the same time). I would prefer to not (explicitly) use any
WINDOW
, if possible. Awhile
loop around getch(), checking for a specific return value is OK too.