Example (_spawnl - _spawnvpe -- Start and Run Child Processes)

This example calls four of the eight _spawn routines. When called without arguments from the command line, the program first runs the code for case PARENT. It spawns a copy of itself, waits for its child process to run, and then spawns a second child process. The instructions for the child process are blocked to run only if argv[0] and one parameter were passed (case CHILD). In its turn, each child process spawns a grandchild as a copy of the same program. The grandchild instructions are blocked by the existence of two passed parameters. The grandchild process can overlay the child process. Each of the processes prints a message identifying itself.

 #include  <stdio.h>
 #include  <process.h>
 #define   PARENT        1
 #define   CHILD         2
 #define   GRANDCHILD    3
 int main(int argc, char **argv, char **envp)
 {
    int    result;
    char   *args[4];
    switch(argc)
    {
       case PARENT:     /* no argument was passed:  spawn child and wait */
          result = spawnle(P_WAIT, argv[0], argv[0], "one", NULL, envp);
          if (result)
              abort();
          args[0] = argv[0];
          args[1] = "two";
          args[2] = NULL;
          /* spawn another child, and wait for it */
          result = spawnve(P_WAIT, argv[0], args, envp);
          if (result)
              abort();
          printf("Parent process ended\n");
          exit(0);
       case CHILD:     /* one argument passed:  allow grandchild to overlay */
          printf("child process %s began\n", argv[1]);
          if (*argv[1] == 'o')            /* child one? */
          {
             spawnl(P_OVERLAY, argv[0], argv[0], "one", "two", NULL);
             abort();       /* not executed because child was overlaid */
          }
          if (*argv[1] == 't')            /* child two? */
          {
              args[0] = argv[0];
              args[1] = "two";
              args[2] = "one";
              args[3] = NULL;
              spawnv(P_OVERLAY, argv[0], args);
              abort();       /* not executed because child was overlaid */
          }
          abort();       /* argument not valid */
      case GRANDCHILD:   /* two arguments passed */
         printf("grandchild %s ran\n", argv[1]);
         exit(0);
    }
    /**************************************************************************
       The output should be similar to:
        child process one began
        grandchild one ran
        child process two began
        Parent process ended
        grandchild two ran
    **************************************************************************/
 }