fork(1) 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. // 创建第一个子进程
  10. pid1 = fork();
  11.  
  12. if (pid1 < 0) {
  13. fprintf(stderr, "Fork Failed\n");
  14. return 1;
  15. } else if (pid1 == 0) {
  16. // 子进程1
  17. printf("b");
  18. fflush(stdout); // 立即刷新输出缓冲区
  19. return 0; // 子进程1结束
  20. }
  21.  
  22. // 父进程继续执行,创建第二个子进程
  23. pid2 = fork();
  24.  
  25. if (pid2 < 0) {
  26. fprintf(stderr, "Fork Failed\n");
  27. return 1;
  28. } else if (pid2 == 0) {
  29. // 子进程2
  30. printf("c");
  31. fflush(stdout); // 立即刷新输出缓冲区
  32. return 0; // 子进程2结束
  33. }
  34.  
  35. // 父进程
  36. // 等待两个子进程都结束
  37. wait(NULL);
  38. wait(NULL);
  39.  
  40. printf("a");
  41. fflush(stdout);
  42.  
  43. return 0;
  44. }
Success #stdin #stdout 0s 5320KB
stdin
Standard input is empty
stdout
cba