fork(2) 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. return 0; // 主函数正常返回
  27. } // ✅ 补全主函数右大括号
Success #stdin #stdout 0s 5320KB
stdin
Standard input is empty
stdout
1