Hey all. The solution to this might be very simple, but I can't figure it out.
I was able to dumb my code down to this:
Code:
int main()
{
char msg[512];
printf("Enter a message: ");
fgets(msg,sizeof msg, stdin);
printf("Entered: %s",msg);
printf("Hold on while we wait 3 seconds...\n");
usleep(3000000);
printf("Wait is over.\n");
printf("Enter another message: ");
fgets(msg,sizeof msg, stdin);
printf("Entered: %s",msg);
return 0;
}
Looks simple enough: read in a message, wait 3 seconds, read in another message.
When I wait 3 seconds like I'm supposed to, everything works according to plan. But when I enter the first message, then during the 3 second pause enter several messages, something unexpected occurs. Even during usleep, things entered in the terminal get pushed onto stdin. Then the second message is interpreted as the very first thing entered AFTER the first message, in this case occurring during the 3 second pause:
Enter a message: 1
Entered: 1
Hold on while we wait 3 seconds...
2 (<--- now during the pause I flood the input with garbage that I want ignored)
3
4
5
Wait is over.
Enter another message: Entered: 2
-bash: 3: command not found
-bash: 4: command not found
-bash: 5: command not found
My goal is that once the program gets to the second call to fgets(), it prompts the user for input and blocks until that input is given. Instead of this happening, it is immediately taking the first thing entered during the 3 second pause.
So I either need a way of blocking stdin during the pause, or a way of clearing stdin immediately following the pause. I have tried fflush(stdin) and rewind(stdin).
Thanks