Advertisement
Doragonroudo

[SysPro] Fork, Wait, Zombie

Feb 15th, 2019
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.04 KB | None | 0 0
  1. // fork.c
  2. #include <sys/types.h>
  3. #include <unistd.h>
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6.  
  7. int main()
  8. {
  9.     pid_t pid; char *msg; int n;
  10.    
  11.     printf("fork program starting\n");
  12.     pid = fork();
  13.     switch(pid)
  14.     {
  15.         case -1: exit(1);
  16.         case 0: msg = "Child!\n"; n = 45; break;
  17.         default: msg = "Parent!\n"; n = 3; break;
  18.     }
  19.    
  20.     for (; n>0; n--) { puts(msg); sleep(1); }
  21.     exit(0);
  22. }
  23.  
  24. // wait.c
  25. #include <sys/types.h>
  26. #include <sys/wait.h>
  27. #include <unistd.h>
  28. #include <stdio.h>
  29. #include <stdlib.h>
  30.  
  31. int main()
  32. {
  33.     pid_t pid; char *msg; int n;
  34.     printf("fork program starting\n");
  35.     pid = fork();
  36.     switch(pid)
  37.     {
  38.         case -1: exit(1);
  39.         case 0: msg = "Child!\n"; n = 45; break;
  40.         default: msg = "Parent!\n"; n = 3; break;
  41.     }
  42.     for (; n>0; n--) { puts(msg); sleep(1); }
  43.     if (pid)
  44.     {
  45.         int stat_val; pid_t child_pid;
  46.         child_pid = wait(&stat_val);
  47.         printf("Child has finished: PID = %d\n",
  48.                child_pid);
  49.         if (WIFEXITED(stat_val))
  50.             printf("Child exited with code %d\n",
  51.                    WEXITSTATUS(stat_val));
  52.         else
  53.             printf("Child terminated abnormally\n");
  54.     }
  55.     exit(0);
  56. }
  57.  
  58. // zombie.c
  59. #include <sys/types.h>
  60. #include <sys/wait.h>
  61. #include <unistd.h>
  62. #include <stdio.h>
  63. #include <stdlib.h>
  64.  
  65. int main()
  66. {
  67.     pid_t pid; char *msg; int n;
  68.     printf("fork program starting\n");
  69.     pid = fork();
  70.     switch(pid)
  71.     {
  72.         case -1: exit(1);
  73.         case 0: msg = "Child!\n"; n = 3; break;
  74.         default: msg = "Parent!\n"; n = 45; break;
  75.     }
  76.     for (; n>0; n--) { puts(msg); sleep(1); }
  77.    
  78.     if (pid)
  79.     {
  80.         int stat_val; pid_t child_pid;
  81.         child_pid = wait(&stat_val);
  82.         printf("Child has finished: PID = %d\n", child_pid);
  83.         if (WIFEXITED(stat_val))
  84.             printf("Child exited with code %d\n", WEXITSTATUS(stat_val));
  85.         else
  86.             printf("Child terminated abnormally\n");
  87.     }
  88.     exit(0);
  89. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement