| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 
 |  
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/time.h>
 
static int input_timeout(int filedes, unsigned int seconds)
{
  fd_set set;
  struct timeval timeout;
 
  /* 
   * Initialize the file descriptor set. 
   */
  FD_ZERO(&set);
  FD_SET(filedes, &set);
 
  /* 
   * Initialize the timeout data structure. 
   */
  timeout.tv_sec = seconds;
  timeout.tv_usec = 0;
 
  /* 
   * select returns 0 if timeout, 1 if input available, -1 if error. 
   */
  return select(FD_SETSIZE, &set, NULL, NULL, &timeout);
}
 
static void get_and_display(FILE *f)
{
#define MAXLEN 10
  char line[MAXLEN];
  char *p;
 
  fgets(line, sizeof line, f);
 
  p = strchr(line, '\n');
  if (p != NULL)
  {
    *p = '\0';
  }
  else
  {
    fprintf(stderr, "Line too long: Will be truncated.\n");
    line[MAXLEN - 1] = '\0';
    {
      /*
       * empty the stdin buffer
       */
      int c;
      while ((c = fgetc(f)) != '\n' && c!= EOF);
    }
  }
#undef MAXLEN
 
  printf("You entered %s.\n", line);
}
 
int main (void)
{
  int ret;
  int seconds = 5;
 
  printf("You have %d seconds to enter something.\n", seconds);
  ret = input_timeout(STDIN_FILENO, seconds);
 
  switch (ret)
  {
    case 1:
      get_and_display(stdin);
      break;
    case 0:
      printf("Time elapsed.\n");
      break;
    case -1:
      perror("select() on standard input");
  }
 
  return 0;
} | 
Partager