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, wpid;
  8. int status;
  9.  
  10. printf("Parent process started (PID: %d)\n", getpid());
  11.  
  12. // Create a child process using fork()
  13. pid = fork();
  14.  
  15. if (pid < 0) {
  16. // fork failed
  17. perror("fork failed");
  18. exit(EXIT_FAILURE);
  19. } else if (pid == 0) {
  20. // Child process
  21. printf("Child process (PID: %d), parent PID: %d\n", getpid(), getppid());
  22.  
  23. // Replace the child process with a new program using execl
  24. printf("Child process will now execute 'ls -l' command\n");
  25. execl("/bin/ls", "ls", "-l", NULL);
  26.  
  27. // If execl returns, it means it failed
  28. perror("execl failed");
  29. exit(EXIT_FAILURE);
  30. } else {
  31. // Parent process
  32. printf("Parent process waiting for child (PID: %d) to complete\n", pid);
  33.  
  34. // Wait for the child process to complete
  35. wpid = wait(&status);
  36.  
  37. if (wpid == -1) {
  38. perror("wait error");
  39. exit(EXIT_FAILURE);
  40. }
  41.  
  42. if (WIFEXITED(status)) {
  43. printf("Child process %d exited with status %d\n", wpid, WEXITSTATUS(status));
  44. } else if (WIFSIGNALED(status)) {
  45. printf("Child process %d killed by signal %d\n", wpid, WTERMSIG(status));
  46. }
  47.  
  48. printf("Parent process (PID: %d) exiting\n", getpid());
  49. exit(EXIT_SUCCESS);
  50. }
  51. }
Success #stdin #stdout 0s 5304KB
stdin
Standard input is empty
stdout
total 16
-rwxr-xr-x 1 root root 14312 May 21 10:26 prog
Parent process started (PID: 3626140)
Parent process waiting for child (PID: 3626144) to complete
Child process 3626144 exited with status 0
Parent process (PID: 3626140) exiting