Example (execl - _execvpe -- Load and Run Child Process)

This example calls four of the eight exec routines. When invoked without arguments, the program first runs the code for case PARENT. It then calls execle() to load and run a copy of itself. The instructions for the child are blocked to run only if argv[0] and one parameter were passed (case CHILD). In its turn, the child runs its own child as a copy of the same program. This sequence is continued until four generations of child processes have run. Each of the processes prints a message identifying itself.

#include <stdio.h>
#include <stdlib.h>
#include <process.h>
#define  PARENT       1
#define  CHILD        2
char *args[3];
int main(int argc, char **argv, char **envp) {
   switch(argc) {
      case PARENT: {                   /* No argument: run a child */
         printf("Parent process began.\n");
         execle(argv[0],argv[0],"1",NULL,envp);
         abort();     /* Not executed because parent was overlaid. */
      }
      case CHILD: {           /* One argument: run a child's child */
         printf("Child process %s began.\n", argv[1]);
         if ('1' == *argv[1]) {   /* generation one */
            execl(argv[0], argv[0], "2", NULL);
            abort();    /* Not executed because child was overlaid */
        }
        if('2' == *argv[1]) {                    /* generation two */
            args[0] = argv[0];
            args[1] = "3";
            args[2] = NULL;
            execv(argv[0],args);
            abort();    /* Not executed because child was overlaid */
         }
         if ('3' == *argv[1]) {                /* generation three */
            args[0] = argv[0];
            args[1] = "4";
            args[2] = NULL;
            execve(argv[0], args, _environ);
            abort();    /* Not executed because child was overlaid */
        }
         if ('4' == *argv[1])                   /* generation four */
            printf("Child process %s", argv[1]);
      }
   }
   printf(" ended.\n");
   return 55;
   /* The output should be similar to:
      Parent process began.
      Child process 1 began.
      Child process 2 began.
      Child process 3 began.
      Child process 4 began.
      Child process 4 ended.                                        */
}