main.c 1.3 KB

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