Starting a process with the posix_spawn() call
As we mentioned earlier, spawn() and spawnp() were in a POSIX draft, but never made it into the standard. Instead, POSIX added posix_spawn() and posix_spawnp().
The posix_spawn() and posix_spawnp() functions were designed to let you specify how and what the child process should run. They were also designed to be easily extended; their arguments include a pointer to a posix_spawnattr_t structure that specifies spawn attributes, and a pointer to a posix_spawn_file_actions_t structure that specifies file actions (e.g., which file descriptors to close or duplicate in the child). These are both opaque structures, so there are functions that you can use to initialize, get, and set values within them.
For the attributes—some of which are POSIX, and some of which are QNX OS extensions—the first step is to set the members of the attribute structure to their default values by calling posix_spawnattr_init(). To set an attribute, call the appropriate posix_spawnattr_*() function and set the corresponding flag. To set the POSIX flags, call posix_spawnattr_setflags(); to set the QNX OS flags, call posix_spawnattr_setxflags(). For example:
- To set the child's process group (a POSIX attribute), include POSIX_SPAWN_SETPGROUP in the call to posix_spawnattr_setflags(), and call posix_spawnattr_setpgroup() to set the process group.
- To set the child's process runmask (a QNX OS attribute that controls which processors the child can run on), include POSIX_SPAWN_EXPLICIT_CPU in the call to posix_spawnattr_setxflags(), and call pthread_spawnattr_setrunmask_np() to set the runmask.
Setting the file actions is simpler because there are no flags to set; you just call posix_spawn_file_actions_init(), and then call the appropriate posix_spawn_file_actions_*() functions.
When you're ready to create the new process, call posix_spawn() or posix_spawnp(). The difference between these functions is as follows:
- for posix_spawn() you specify the absolute path to the executable
- for posix_spawnp() you specify the name of the executable file, and the function looks for it in the directories listed in your PATH environment variable
For more information, see the entry for these functions in the C Library Reference.