fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <sys/types.h>
  5. #include <sys/wait.h>
  6.  
  7. int main() {
  8. pid_t pid;
  9.  
  10. printf("Starting program (PID: %d)\n", getpid());
  11.  
  12. // fork() system call to create a new process
  13. pid = fork();
  14.  
  15. if (pid < 0) {
  16. // Error occurred
  17. fprintf(stderr, "Fork Failed\n");
  18. return 1;
  19. }
  20. else if (pid == 0) {
  21. // Child Process
  22. printf("\n[Child] Created (PID: %d)\n", getpid());
  23. printf("[Child] Parent PID: %d\n", getppid());
  24. printf("[Child] Performing task and exiting...\n");
  25. sleep(2); // Simulate work
  26. exit(0); // Exit system call
  27. }
  28. else {
  29. // Parent Process
  30. printf("\n[Parent] Created child with PID: %d\n", pid);
  31. printf("[Parent] Waiting for child to finish...\n");
  32.  
  33. // wait() system call to wait for child completion
  34. wait(NULL);
  35.  
  36. printf("\n[Parent] Child finished.\n");
  37. printf("[Parent] Exiting.\n");
  38. }
  39.  
  40. return 0;
  41. }
  42.  
Success #stdin #stdout 0s 5308KB
stdin
Standard input is empty
stdout
Starting program (PID: 3372126)

[Child] Created (PID: 3372129)
[Child] Parent PID: 3372126
[Child] Performing task and exiting...
Starting program (PID: 3372126)

[Parent] Created child with PID: 3372129
[Parent] Waiting for child to finish...

[Parent] Child finished.
[Parent] Exiting.