Since you have fcntl.h , try installing stdin for non-blocking. This is not very (active waiting), but if you do not have select , then this is the easiest way:
#include <stdio.h> #include <string.h> #include <time.h> #include <stdlib.h> #include <fcntl.h> #include <errno.h> int main() { // get stdin flags int flags = fcntl(0, F_GETFL, 0); if (flags == -1) { // fcntl unsupported perror("fcntl"); return -1; } // set stdin to non-blocking flags |= O_NONBLOCK; if(fcntl(0, F_SETFL, flags) == -1) { // fcntl unsupported perror("fcntl"); return -1; } char st[1024] = {0}; // initialize the first character in the buffer, this is generally good practice printf ("Please enter a line of text : "); time_t end = time(0) + 5; //5 seconds time limit. // while while(time(0) < end // not timed out && scanf("%s", st) < 1 // not read a word && errno == EAGAIN); // no error, but would block if (st[0]) // if the buffer contains something printf ("Thank you, you entered >%s<\n", st); return 0; }
Note to your code: if (st != NULL) will always execute, since st is a stack pointer.
source share