fork download
  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <sys/types.h>
  4. #include <sys/wait.h>
  5.  
  6. int main() {
  7. pid_t pid1, pid2;
  8.  
  9. pid1 = fork();
  10. if (pid1 < 0) {
  11. fprintf(stderr, "Fork Failed\n");
  12. return 1;
  13. } else if (pid1 == 0) {
  14. lockf(1, 1, 0);
  15. printf("饿\n");
  16. fflush(stdout);
  17. lockf(1, 0, 0);
  18. return 0;
  19. }
  20.  
  21. // 父进程先等子进程1结束,再创建子进程2
  22. waitpid(pid1, NULL, 0);
  23.  
  24. pid2 = fork();
  25. if (pid2 < 0) {
  26. fprintf(stderr, "Fork Failed\n");
  27. return 1;
  28. } else if (pid2 == 0) {
  29. lockf(1, 1, 0);
  30. printf("吃饭\n");
  31. fflush(stdout);
  32. lockf(1, 0, 0);
  33. return 0;
  34. }
  35.  
  36. // 再等子进程2结束
  37. waitpid(pid2, NULL, 0);
  38.  
  39. lockf(1, 1, 0);
  40. printf("饿就吃饭\n");
  41. fflush(stdout);
  42. lockf(1, 0, 0);
  43.  
  44. return 0;
  45. }
Success #stdin #stdout 0s 5328KB
stdin
Standard input is empty
stdout
饿
吃饭
饿就吃饭