source code of /small-scripts/stackexchange/chainfork.c

Last modified
Lines 37

Parent directory Download CGIread sitemap Main page

Quick links: (none)

  1. #include <pthread.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <sys/types.h>
  5. #include <unistd.h>
  6. #include <sys/wait.h>
  7. #define N_PROCS 42
  8. int main(int argc, char *argv[])
  9. {
  10.     int i;
  11.     pid_t child;
  12.     int status;
  13.     for (i = 0; i < N_PROCS; i++)
  14.     {
  15.         child = fork();
  16.         if (-1 == child)
  17.         {
  18.             fprintf(stderr, "fork() failed\n");
  19.             return 1;
  20.         }
  21.         /*
  22.          * The next iteration of the loop will only be executed
  23.          * by the child process.
  24.          */
  25.         if (child) break;
  26.     }
  27.     printf("I'm process #%d (PID=%d)\n", i, (long)getpid());
  28.     /*
  29.      * On the last iteration of the while loop, child is zero
  30.      * for the last process in the chain.
  31.      */
  32.     if (child) wait(&status);
  33.     return 0;
  34. }