fork download
  1. #include <stdio.h>
  2. #include <unistd.h> // for fork(), getpid(), getppid()
  3. #include <sys/wait.h> // for wait()
  4. #include <stdlib.h> // for exit()
  5.  
  6. int main() {
  7. pid_t pid;
  8.  
  9. // Create a child process
  10. pid = fork();
  11.  
  12. if (pid < 0) {
  13. // fork() failed
  14. perror("fork failed");
  15. exit(1);
  16. }
  17. else if (pid == 0) {
  18. // Child process
  19. printf("Child Process:\n");
  20. printf(" PID: %d\n", getpid());
  21. printf(" Parent PID: %d\n", getppid());
  22. }
  23. else {
  24. // Parent process
  25. printf("Parent Process:\n");
  26. printf(" PID: %d\n", getpid());
  27. printf(" Parent PID: %d\n", getppid());
  28.  
  29. // Parent waits for child to finish
  30. wait(NULL);
  31. printf("Child process (PID: %d) finished. Parent terminating.\n", pid);
  32. }
  33.  
  34. return 0;
  35. }
  36.  
Success #stdin #stdout 0.01s 5320KB
stdin
Standard input is empty
stdout
Child Process:
  PID: 1655578
  Parent PID: 1655535
Parent Process:
  PID: 1655535
  Parent PID: 1655534
Child process (PID: 1655578) finished. Parent terminating.