From d8e0504ad02042df41612da0ea4e39440316c1fe Mon Sep 17 00:00:00 2001 From: ArthurSonzogni Date: Fri, 1 May 2020 23:33:21 +0200 Subject: [PATCH] Add timeout for getchar() in POSIX. Previously, the thread pooling new characters being typed was waiting for "one more char" being typed before being able to exit. This patch adds a timeout for getchar(). This way, event if the user do not press his/her keyboard, the program is still able to exit. This fixes issue: https://github.com/GiuseppeCesarano/just-fast/issues/2 --- src/ftxui/component/screen_interactive.cpp | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/src/ftxui/component/screen_interactive.cpp b/src/ftxui/component/screen_interactive.cpp index 3eef2262..439dd7f4 100644 --- a/src/ftxui/component/screen_interactive.cpp +++ b/src/ftxui/component/screen_interactive.cpp @@ -26,6 +26,7 @@ #else #include #include + #include #endif // Quick exit is missing in standard CLang headers @@ -94,10 +95,21 @@ void Win32EventListener(std::atomic* quit, // Read char from the terminal. void UnixEventListener(std::atomic* quit, Sender sender) { - // TODO(arthursonzogni): Use a timeout so that it doesn't block even if the - // user doesn't generate new chars. - while (!*quit) - sender->Send((char)getchar()); + fd_set readfds; + FD_ZERO(&readfds); + + struct timeval timeout; + timeout.tv_sec = 0; + timeout.tv_usec = 300000; + + while (!*quit) { + FD_SET(STDIN_FILENO, &readfds); + if (!select(1, &readfds, NULL, NULL, &timeout)) + continue; + + char c = getchar(); + sender->Send(c); + } } #endif