If you are running on a POSIX or POSIX-like system such as Linux or Mac OS X, you can use signals and e.g. setitimer() or timer_create()/timer_settime() to implement an interval timer that generates the interrupt at desired intervals.
Note that you can only use Async-signal safe function (list at about halfway down, look for that header) in a signal handler.
Signal delivery interrupts I/O functions. scanf() family of functions will return EOF, with errno==EINTRand fgets() will return NULL, with errno==EINTR, and so on. Therefore, if you have a scanf() call that reads e.g. an integer, you can do
Code:
int result;
int value;
while (1) {
result = scanf("%d", &value);
if (result == 1)
break; /* Scanned 'value' successfully. */
if (result != EOF) {
fprintf(stderr, "Input was not an integer.\n");
/* Note: the non-integer data is still in input, so you cannot just
* try re-parsing it. You'll need to either abort (as I do here),
* or somehow consume the offending data before retrying. */
return 1;
}
if (errno != EINTR) {
fprintf(stderr, "Error reading standard input: %s.\n", strerror(errno));
return 1;
}
/* result == EOF && errno == EINTR,
* which means an interrupt occurred.
* Therefore, just retry.
*/
}
/* Have 'value'. */
If the thing you need to do once every second or so is something like printing a clock or something, you can do that at the end of the above loop. In that case, you still need to set up a signal handler, but the handler function itself can have an empty body. (The point is that when the signal is delivered to your function, the blocking I/O functions are interrupted. It's the delivery that is important thing here, not the signal itself.)
Another approach is to use threads. One thread will read the user input, while the other thread will do whatever work needs to be done, and waits for about a second in between. The threaded approach has the benefit that you are not limited to async-signal safe functions in your timer code.