test_eventfd.c 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. #include <err.h>
  2. #include <inttypes.h>
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <sys/eventfd.h>
  6. #include <sys/types.h>
  7. #include <unistd.h>
  8. int main(int argc, char *argv[]) {
  9. int efd;
  10. uint64_t u;
  11. ssize_t s;
  12. if (argc < 2) {
  13. fprintf(stderr, "Usage: %s <num>...\n", argv[0]);
  14. exit(EXIT_FAILURE);
  15. }
  16. efd = eventfd(0, 0);
  17. if (efd == -1)
  18. err(EXIT_FAILURE, "eventfd");
  19. switch (fork()) {
  20. case 0:
  21. for (size_t j = 1; j < argc; j++) {
  22. printf("Child writing %s to efd\n", argv[j]);
  23. u = strtoull(argv[j], NULL, 0);
  24. /* strtoull() allows various bases */
  25. s = write(efd, &u, sizeof(uint64_t));
  26. if (s != sizeof(uint64_t))
  27. err(EXIT_FAILURE, "write");
  28. }
  29. printf("Child completed write loop\n");
  30. exit(EXIT_SUCCESS);
  31. default:
  32. sleep(2);
  33. printf("Parent about to read\n");
  34. s = read(efd, &u, sizeof(uint64_t));
  35. if (s != sizeof(uint64_t))
  36. err(EXIT_FAILURE, "read");
  37. printf("Parent read %" PRIu64 " (%#" PRIx64 ") from efd\n", u, u);
  38. exit(EXIT_SUCCESS);
  39. case -1:
  40. err(EXIT_FAILURE, "fork");
  41. }
  42. }