Starting a process with the posix_spawn() call

Updated: April 19, 2023

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 Neutrino 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 Neutrino flags, call posix_spawnattr_setxflags(). For example:

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 more information, see the entry for these functions in the C Library Reference.