ChorusOS 5.0 Application Developer's Guide

Spawning a Process

A process can spawn another process dynamically using the posix_spawn() or posix_spawnp() function. This spawned process can be either a supervisor or a user process.

Example 3-3 creates a new process. The spawned process executes a binary file stored in the file named path. Note that the example uses posix_spawnp() and not posix_spawn(). The posix_spawnp() function searches for the binary file in all directories specified by the PATH environment variable. If you use posix_spawn() instead, you must specify the full path to the binary file.

The main thread of this process runs the main routine of the program. This thread has the same scheduling attributes and stack size as an embedded actor loaded manually.

argv and spawnedEnv are pointers to the array of arguments and environments that are received by the newly created process.

If successful, all posix_spawn() and posix_spawnp() routines return 0. Otherwise, they return an error code.


Note -

The value of errno is unspecified.


In the example:


Example 3-3 Spawning a Process

#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <span.h>
#include <string.h>

char*   spawnedArgs[3];
char*   spawnedEnv[1];
char*   tagPtr = "Welcome newly created process!";

int main(int argc, char* argv[])
{
  int          res;
  pid_t        pid;
  
  if (argc == 1) {
        /*
         * This is the first process (or spawning process):
         *   Binary file used to load this process is passed
         *   as argv[0],
         *
         *   Set an argument in order to enable the second
         *   process to know it is the second one.
         */
    spawnedArgs[0] = argv[0];
    spawnedArgs[1] = tagPtr;
    spawnedArgs[2] = NULL;
    spawnedEnv[0] = NULL;
    res = posix_spawnp(&pid, spawnedArgs[0], NULL, 
          NULL, spawnedArgs, spawnedEnv);
    if (res != 0) {
      printf("Cannot spawn second process, error %d\n", res);
      exit(1);
    }
    printf("I successfully created a process whose pid is %d\n", pid);
  } else {
        /*
         * This is the spawned process:
         *   Check the number of args,
         *   Print args,
         *   Exit
         */
    if ((argc == 2) && (strcmp(tagPtr, argv[1]) == 0)) {
            /*
             * This is really the spawned process.
             */
        printf("My spawning process passed me this argument: %s\n",
               argv[1]);
    } else {
        printf("You ran %s with an argument. Do not!\n", argv[0]);
        exit(1);
    }
  }
  exit(0);
}