29

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. A while loop around getch(), checking for a specific return value is OK too.

Jonas Byström
  • 25,316
  • 23
  • 100
  • 147

3 Answers3

42

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;
}
Norman Ramsey
  • 198,648
  • 61
  • 360
  • 533
11

From a man page (emphasis added):

The timeout and wtimeout routines set blocking or non-blocking read for a given window. If delay is negative, blocking read is used (i.e., waits indefinitely for input).

Rob Kennedy
  • 161,384
  • 21
  • 275
  • 467
  • #include void main() { timeout(-3000000); getch(); } does not block for me. Any clues? – Jonas Byström May 25 '09 at 01:55
  • 7
    It's assumed that you're using the rest of curses properly, including initialization. – Rob Kennedy May 25 '09 at 03:09
  • @JonasByström Of course the fact you declared main() void is, last I knew, undefined, which means the entire state of the program is not to be trusted. If nothing else though it's broken whether or not it appears to work (I say 'last I knew' but really I mean I’m uncertain off hand at this moment if it's by way of making it undefined but either way it's broken code). – Pryftan Apr 22 '19 at 13:36
  • 3
    @Pryftan Ever since the dawn of time, all of the following were legal C main prototypes: `void main(void), int main(void), int main(int argc, const char* argv[]), int main(int argc, const char* argv[], char* envp[])`. Just because you don't know about it does not make it undefined ;) – BitTickler Feb 16 '21 at 14:45
10

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);
}
cjs
  • 25,752
  • 9
  • 89
  • 101