select.c 1008 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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. write(fd[1], string, (strlen(string) + 1));
  30. ret = select(fd[1] + 1, &rfds, NULL, NULL, &tv);
  31. if (ret <= 0) {
  32. perror("select() on read event failed");
  33. return 1;
  34. }
  35. printf("select() on read event returned %d file descriptors\n", ret);
  36. return 0;
  37. }