select.c 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /* Waiting for Input or Output
  2. Copyright (C) 1991-2026 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 <https://www.gnu.org/licenses/>.
  13. */
  14. /*@group*/
  15. #define _GNU_SOURCE 1
  16. #include <errno.h>
  17. #include <stdio.h>
  18. #include <unistd.h>
  19. #include <sys/types.h>
  20. #include <sys/select.h>
  21. /*@end group*/
  22. /*@group*/
  23. int
  24. input_timeout (int filedes, unsigned int seconds)
  25. {
  26. fd_set set;
  27. struct timeval timeout;
  28. /*@end group*/
  29. /* Initialize the file descriptor set. */
  30. FD_ZERO (&set);
  31. FD_SET (filedes, &set);
  32. /* Initialize the timeout data structure. */
  33. timeout.tv_sec = seconds;
  34. timeout.tv_usec = 0;
  35. /*@group*/
  36. /* @code{select} returns 0 if timeout, 1 if input available, -1 if error. */
  37. return TEMP_FAILURE_RETRY (select (FD_SETSIZE,
  38. &set, NULL, NULL,
  39. &timeout));
  40. }
  41. /*@end group*/
  42. /*@group*/
  43. int
  44. main (void)
  45. {
  46. fprintf (stderr, "select returned %d.\n",
  47. input_timeout (STDIN_FILENO, 5));
  48. return 0;
  49. }
  50. /*@end group*/