select.c 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <sys/select.h>
  4. #include <sys/time.h>
  5. #include <sys/types.h>
  6. #include <unistd.h>
  7. int main(void) {
  8. fd_set rfds;
  9. fd_set wfds;
  10. int ret;
  11. int fd[2];
  12. char string[] = "Hello, world!\n";
  13. struct timeval tv = {.tv_sec = 10, .tv_usec = 0};
  14. ret = pipe(fd);
  15. if (ret < 0) {
  16. perror("pipe creation failed");
  17. return 1;
  18. }
  19. FD_ZERO(&rfds);
  20. FD_ZERO(&wfds);
  21. FD_SET(fd[0], &rfds);
  22. FD_SET(fd[1], &wfds);
  23. ret = select(fd[1] + 1, NULL, &wfds, NULL, &tv);
  24. if (ret <= 0) {
  25. perror("select() on write event failed");
  26. return 1;
  27. }
  28. printf("select() on write event returned %d file descriptors\n", ret);
  29. size_t len = strlen(string) + 1;
  30. if (write(fd[1], string, len) != len) {
  31. perror("write error");
  32. return 1;
  33. }
  34. ret = select(fd[1] + 1, &rfds, NULL, NULL, &tv);
  35. if (ret <= 0) {
  36. perror("select() on read event failed");
  37. return 1;
  38. }
  39. printf("select() on read event returned %d file descriptors\n", ret);
  40. return 0;
  41. }