posix_spawn()

QNX SDP8.0System ArchitectureDeveloperUser

The posix_spawn() function creates a child process by directly specifying an executable to load.

To those familiar with UNIX systems, the posix_spawn() call is modeled after a fork() followed by an exec*(). However, it operates much more efficiently in that there's no need to duplicate address spaces as in a fork(), only to destroy and replace it when the exec*() is called.

In a UNIX system, one of the main advantages of using the fork()-then-exec*() method of creating a child process is the flexibility in changing the default environment inherited by the new child process. This is done in the forked child just before the exec*(). For example, the following simple shell command would close and reopen the standard output before exec*()'ing:
ls >file

You can do the same with posix_spawn(); it gives you control over the following classes of environment inheritance, which are often adjusted when creating a new child process:

  • file descriptors
  • process user and group IDs
  • signal mask
  • ignored signals

There's also a companion function, posix_spawnp(), that doesn't require the absolute path to the program to spawn, but instead searches for the executable using the caller's PATH.

Using the posix_spawn() functions is the preferred way to create a new child process.

Page updated: