fork(5) download
  1. #include <stdio.h>
  2. #include <unistd.h> // fork()
  3. #include <sys/types.h> // pid_t
  4. #include <stdlib.h> // exit()
  5. #include <sys/wait.h> // wait()
  6.  
  7. int main() {
  8. pid_t pid1, pid2;
  9.  
  10. // 创建第一个子进程
  11. pid1 = fork();
  12. if (pid1 < 0) {
  13. perror("fork 失败");
  14. exit(1);
  15. }
  16.  
  17. if (pid1 == 0) {
  18. // 第一个子进程
  19. printf("1\n");
  20. exit(0);
  21. }
  22.  
  23. // 等待第一个子进程结束
  24. wait(NULL);
  25.  
  26. // 创建第二个子进程
  27. pid2 = fork();
  28. if (pid2 < 0) {
  29. perror("fork 失败");
  30. exit(1);
  31. }
  32.  
  33. if (pid2 == 0) {
  34. // 第二个子进程
  35. printf("2\n");
  36. exit(0);
  37. }
  38.  
  39. // 等待第二个子进程结束
  40. wait(NULL);
  41.  
  42. printf("父进程执行完毕\n");
  43.  
  44. return 0;
  45. }
Success #stdin #stdout 0s 5304KB
stdin
Standard input is empty
stdout
1
2
父进程执行完毕