fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <sys/wait.h>
  5.  
  6. int main() {
  7. pid_t pid = fork(); // First fork
  8.  
  9. if (pid == 0) { // Child process
  10. printf("Child 1: PID=%d\n", getpid());
  11.  
  12. // Forking again
  13. pid_t pid_child2 = fork();
  14.  
  15. if (pid_child2 == 0) { // Child of child process
  16. printf("Child 2: PID=%d, Parent PID=%d\n", getpid(), getppid());
  17. printf("Child 2: Exiting...\n");
  18. exit(EXIT_SUCCESS);
  19. } else if (pid_child2 > 0) { // Parent process (Child 1)
  20. printf("Child 1: Waiting for Child 2 to finish...\n");
  21. waitpid(pid_child2, NULL, 0); // Wait for Child 2 to finish
  22. printf("Child 1: Exiting...\n");
  23. exit(EXIT_SUCCESS);
  24. } else { // Error handling for second fork
  25. perror("fork");
  26. exit(EXIT_FAILURE);
  27. }
  28. } else if (pid > 0) { // Parent process
  29. printf("Parent: PID=%d\n", getpid());
  30. printf("Parent: Waiting for Child 1 to finish...\n");
  31. waitpid(pid, NULL, 0); // Wait for Child 1 to finish
  32. printf("Parent: Exiting...\n");
  33. } else { // Error handling for first fork
  34. perror("fork");
  35. exit(EXIT_FAILURE);
  36. }
  37.  
  38. return 0;
  39. }
  40.  
Success #stdin #stdout 0.01s 5284KB
stdin
ls | sort
stdout
Child 1: PID=1157256
Child 2: PID=1157257, Parent PID=1157256
Child 2: Exiting...
Child 1: PID=1157256
Child 1: Waiting for Child 2 to finish...
Child 1: Exiting...
Parent: PID=1157253
Parent: Waiting for Child 1 to finish...
Parent: Exiting...