tags:

views:

96

answers:

3

Well, I'm programming using C language on a Linux OS. I'm writing a program that scans an input from the user. However, I want the scanf to have a certain time limit. For example, if the user does not enter anything on the keyboard withing 10 seconds, it will skip the scanf and go to the next line. I'm using alarm(10) to wait for 10 seconds, but when I go to the alarmhandler I don't know what to do to skip the scanf.

Is there a function to skip scanf or for example write \n to the input buffer?

+1  A: 

You can use select(2) or poll(2) to specify a timeout and check if stdin has input.

Bertrand Marron
+1  A: 

Return from the alarm handler; scanf's return value should reflect that an error condition has happened. (scanf returns EOF on error).

NOTE! You MUST use sigaction, as signal might make read(), the system call underlying scanf() automatically restartable.

#include <stdio.h>
#include <signal.h>

void handler(int signo)
{
  return;
}

int main()
{
  int x;
  struct sigaction sa;

  sa.sa_handler = handler;
  sigemptyset(&sa.sa_mask);
  sa.sa_flags = 0;
  sigaction(SIGALRM, &sa, NULL);

  alarm(5);

  if (scanf("%d", &x) == 1)
  {
    printf("%d\n", x);
    alarm(0); // cancel the alarm
  }
  else
  {
    printf("timedout\n");
  }
  return 0;
}
zvrba
A: 

You might want to consider using ncurses instead of standard I/O. It's a bit arcane, but it insulates you from all kinds of coding nuisances (both portability and "you have to code this just exactly right or it won't work reliably, and good luck finding documentation"). And the halfdelay function seems to provide a mode that is precisely what you're looking for here.

Zack