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);
}