I am trying to make a loop that will run infinitely without user input, until 'Enter' is pressed. This is the simplified version of my program:
do {
printf("Hello\n");
}while(!getchar());
When I compile and run the program only output one 'Hello' and the program will not continue, until Enter is pressed then the program will exit. May I know which part am I wrong?
Thank you.
It is not so easy. Your problem is that the standard I/O functions are synchronous. Your getchar
is waiting for some input (a line of input to be precise) and it blocks execution of program until Enter
is pressed. To continue execution without blocking you need to use asynchronous I/O operations or select
(or poll
). Select
allows you to detect whether the next I/O operation would block or not. Look at the documentation of select
and try this:
#include<stdio.h>
#include<unistd.h>
#include <sys/select.h>
int main() {
fd_set s;
struct timeval timeout;
timeout.tv_sec = 0;
timeout.tv_usec = 100000;
do {
printf("Hello\n");
fflush(stdout);
FD_ZERO(&s);
FD_SET(STDIN_FILENO, &s);
select(STDIN_FILENO+1, &s, NULL, NULL, &timeout);
} while (FD_ISSET(STDIN_FILENO, &s) == 0);
}