fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include<sys/types.h>
  4. #include<sys/wait.h>
  5. #include<unistd.h>
  6. int main() {
  7. pid_t pid = fork();
  8. if (pid < 0) {
  9. perror("Fork failed"); exit(1);
  10. }
  11. else if (pid == 0) {
  12. printf("Child process (PID: %d) is runningg.....\n", getpid());
  13. sleep(2); // Simulate some work
  14. printf("Child process (PID: %d) is exiting with status 42.\n", getpid());
  15. exit(42);
  16. }
  17. else {
  18. int status;
  19. pid_t child_pid = wait(&status);
  20. if (WIFEXITED(status)) {
  21. printf("Parent process detected child (PID: %d) exited with status: %d\n", child_pid, WEXITSTATUS(status));
  22. }
  23. printf("Parent process (PID: %d) is exiting normally.\n", getpid());
  24. exit(0);
  25. }
  26. }
  27.  
  28.  
Success #stdin #stdout 0s 5324KB
stdin
Standard input is empty
stdout
Child process (PID: 3919157) is runningg.....
Child process (PID: 3919157) is exiting with status 42.
Parent process detected child (PID: 3919157) exited with status: 42
Parent process (PID: 3919153) is exiting normally.