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;
  8.  
  9. printf("Parent process (PID %d)\n", getpid());
  10.  
  11. pid = fork(); // Create a child process
  12.  
  13. if (pid < 0) {
  14. fprintf(stderr, "Fork failed\n");
  15. return 1;
  16. } else if (pid == 0) {
  17. // Child process
  18. printf("Child process (PID %d)\n", getpid());
  19. sleep(5); // Simulate some work
  20. printf("Child process exiting\n");
  21. exit(0);
  22. } else {
  23. // Parent process
  24. int status;
  25. wait(&status); // Wait for the child process to finish
  26. printf("Parent process exiting\n");
  27. }
  28.  
  29. return 0;
  30. }
  31.  
Success #stdin #stdout 0.01s 5300KB
stdin
Standard input is empty
stdout
Parent process (PID 2160553)
Child process (PID 2160556)
Child process exiting
Parent process (PID 2160553)
Parent process exiting