main.c 908 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. #include <errno.h>
  2. #include <fcntl.h>
  3. #include <stdint.h>
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #include <string.h>
  7. #include <sys/eventfd.h>
  8. #include <sys/select.h>
  9. #include <sys/wait.h>
  10. #include <time.h>
  11. #include <unistd.h>
  12. // 子线程或子进程模拟事件发生
  13. void trigger_event(unsigned int delay_sec) {
  14. printf("[child] triggere event after %u seconds...\n", delay_sec);
  15. sleep(delay_sec);
  16. printf("[child] Event triggered.\n");
  17. }
  18. int main() {
  19. pid_t pid = fork();
  20. if (pid < 0) {
  21. perror("fork");
  22. exit(1);
  23. }
  24. if (pid == 0) {
  25. // 子进程:触发事件
  26. trigger_event(3);
  27. exit(0);
  28. }
  29. // 父进程:使用 select 等待事件发生
  30. printf("[parent] Waiting for child %d exit...\n", pid);
  31. // wait for child process to finish
  32. int status;
  33. waitpid(pid, &status, 0);
  34. printf("[parent] Child exited with status: %d\n", WEXITSTATUS(status));
  35. return 0;
  36. }