fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <sys/wait.h>
  5.  
  6. int main() {
  7. printf("A\n"); // 主行程:印 A(一定最先出現)
  8.  
  9. if (fork() == 0) { // fork 一個子行程 P1
  10.  
  11. printf("B\n"); // P1 印出 B
  12.  
  13. if (fork() == 0) { // P1 fork 出 P2
  14.  
  15. printf("C\n"); // P2 印 C
  16. } else {
  17. wait(NULL); // P1 等 P2 結束
  18. printf("D\n"); // P1 印 D
  19. }
  20.  
  21. } else {
  22.  
  23. printf("E\n"); // 主行程印 E
  24. wait(NULL); // 等 P1 結束
  25. }
  26.  
  27. return 0;
  28. }
Success #stdin #stdout 0.01s 5288KB
stdin
Standard input is empty
stdout
A
B
C
A
B
D
A
E