select.c 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. /* Waiting for Input or Output
  2. Copyright (C) 1991-2019 Free Software Foundation, Inc.
  3. This program is free software; you can redistribute it and/or
  4. modify it under the terms of the GNU General Public License
  5. as published by the Free Software Foundation; either version 2
  6. of the License, or (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program; if not, see <http://www.gnu.org/licenses/>.
  13. */
  14. /*@group*/
  15. #include <errno.h>
  16. #include <stdio.h>
  17. #include <unistd.h>
  18. #include <sys/types.h>
  19. #include <sys/time.h>
  20. /*@end group*/
  21. /*@group*/
  22. int
  23. input_timeout (int filedes, unsigned int seconds)
  24. {
  25. fd_set set;
  26. struct timeval timeout;
  27. /*@end group*/
  28. /* Initialize the file descriptor set. */
  29. FD_ZERO (&set);
  30. FD_SET (filedes, &set);
  31. /* Initialize the timeout data structure. */
  32. timeout.tv_sec = seconds;
  33. timeout.tv_usec = 0;
  34. /*@group*/
  35. /* @code{select} returns 0 if timeout, 1 if input available, -1 if error. */
  36. return TEMP_FAILURE_RETRY (select (FD_SETSIZE,
  37. &set, NULL, NULL,
  38. &timeout));
  39. }
  40. /*@end group*/
  41. /*@group*/
  42. int
  43. main (void)
  44. {
  45. fprintf (stderr, "select returned %d.\n",
  46. input_timeout (STDIN_FILENO, 5));
  47. return 0;
  48. }
  49. /*@end group*/