pselect.c 1.1 KB

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