2
0

select.c 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. #include <fcntl.h>
  2. #include <stdio.h>
  3. #include <sys/select.h>
  4. #include <unistd.h>
  5. #include "test_helpers.h"
  6. int file_test(void) {
  7. int fd = open("select.c", 0, 0);
  8. if (fd < 0) {
  9. perror("open");
  10. return -1;
  11. }
  12. printf("Testing select on file\n");
  13. fd_set read;
  14. FD_ZERO(&read);
  15. FD_SET(fd, &read);
  16. printf("Is set before? %d\n", FD_ISSET(fd, &read));
  17. int nfds = select(fd + 1, &read, NULL, NULL, NULL);
  18. if (nfds < 0) {
  19. perror("select");
  20. return 1;
  21. }
  22. printf("Amount of things ready: %d\n", nfds);
  23. printf("Is set after? %d\n", FD_ISSET(fd, &read));
  24. close(fd);
  25. return 0;
  26. }
  27. int pipe_test(void) {
  28. int pipefd[2];
  29. if (pipe2(pipefd, O_NONBLOCK) < 0) {
  30. perror("pipe");
  31. return 1;
  32. }
  33. char c = 'c';
  34. if (write(pipefd[1], &c, sizeof(c)) < 0) {
  35. perror("write");
  36. return 1;
  37. }
  38. printf("Testing select on pipe\n");
  39. fd_set read;
  40. FD_ZERO(&read);
  41. FD_SET(pipefd[0], &read);
  42. printf("Is set before? %d\n", FD_ISSET(pipefd[0], &read));
  43. int nfds = select(pipefd[0] + 1, &read, NULL, NULL, NULL);
  44. if (nfds < 0) {
  45. perror("select");
  46. return 1;
  47. }
  48. printf("Amount of things ready: %d\n", nfds);
  49. printf("Is set after? %d\n", FD_ISSET(pipefd[0], &read));
  50. close(pipefd[0]);
  51. close(pipefd[1]);
  52. return 0;
  53. }
  54. int main(void) {
  55. if (file_test()) {
  56. return 1;
  57. }
  58. if (pipe_test()) {
  59. return 1;
  60. }
  61. return 0;
  62. }