1
      2
      3
      4
      5
      6
      7
      8
      9
     10
     11
     12
     13
     14
     15
     16
     17
     18
     19
     20
     21
     22
     23
     24
     25
     26
     27
     28
     29
     30
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>

int main() {
   pid_t child, pid; int stat;

   child = fork();
   if (child == -1) {
      perror("unable to fork"); exit(1);
   }
   if (child == 0) {
      /* child process */
      srand(getpid());
      exit(rand());
   }

   /* parent process */
   pid = wait(&stat);
   if (pid == child) {
      if (WIFEXITED(stat)) {
         printf("exit code of child = %d\n", WEXITSTATUS(stat));
      } else {
         printf("child terminated abnormally\n");
      }
   } else {
      perror("wait");
   }
}