fork download
  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <sys/wait.h>
  4.  
  5. void P0() {
  6. int pid1, pid2, pid5;
  7. pid1 = fork();
  8. if (pid1 == 0) {
  9. // processus fils P1
  10. P1();
  11. } else {
  12. // processus Parent P0
  13. wait(NULL);
  14. pid2 = fork();
  15. if (pid2 == 0) {
  16. // processus fils P2
  17. P2();
  18. } else {
  19. // processus Parent P0
  20. wait(NULL);
  21. pid5 = fork();
  22. if (pid5 == 0) {
  23. // Child process P5
  24. P5();
  25. } else {
  26. // processus Parent P0
  27. wait(NULL);
  28. printf("Process P0 finished.\n");
  29. }
  30. }
  31. }
  32. }
  33.  
  34. void P1() {
  35. printf("Process P1 started.\n");
  36.  
  37. printf("Process P1 finished.\n");
  38. }
  39.  
  40. void P2() {
  41. int pid3, pid4;
  42.  
  43. pid3 = fork();
  44. printf("Process P2 started.\n");
  45. if (pid3 == 0) {
  46. // processus fils P3
  47. P3();
  48. } else {
  49. // processus Parent P2
  50. wait(NULL);
  51. pid4 = fork();
  52. if (pid4 == 0) {
  53. // processus fils P4
  54. P4();
  55. } else {
  56. // processus Parent P2
  57. wait(NULL);
  58. printf("Process P2 finished.\n");
  59. }
  60. }
  61. }
  62.  
  63. void P3() {
  64. printf("Process P3 started.\n");
  65.  
  66. printf("Process P3 finished.\n");
  67. }
  68.  
  69. void P4() {
  70. printf("Process P4 started.\n");
  71.  
  72. printf("Process P4 finished.\n");
  73. }
  74.  
  75. void P5() {
  76. printf("Process P5 started.\n");
  77.  
  78. printf("Process P5 finished.\n");
  79. }
  80.  
  81.  
  82. int main() {
  83. P0();
  84. return 0;
  85. }
Success #stdin #stdout 0.01s 5280KB
stdin
Standard input is empty
stdout
Process P1 started.
Process P1 finished.
Process P2 started.
Process P3 started.
Process P3 finished.
Process P2 started.
Process P4 started.
Process P4 finished.
Process P2 started.
Process P2 finished.
Process P5 started.
Process P5 finished.
Process P0 finished.