#include <spawn.h> int posix_spawn(pid_t *pid, const char *path, const posix_spawn_file_actions_t *file_actions, const posix_spawnattr_t *attrp, char *const argv[], char *const envp[]); int posix_spawnp(pid_t *pid, const char *file, const posix_spawn_file_actions_t *file_actions, const posix_spawnattr_t *attrp, char *const argv[], char *const envp[]);
The posix_spawn() and posix_spawnp() functions provide the functionality of a combined fork(2) and exec(3), with some optional housekeeping steps in the child process before the exec(3). These functions are not meant to replace the fork(2) and execve(2) system calls. In fact, they provide only a subset of the functionality that can be achieved by using the system calls.
The only difference between posix_spawn() and posix_spawnp() is the manner in which they specify the file to be executed by the child process. With posix_spawn(), the executable file is specified as a pathname (which can be absolute or relative). With posix_spawnp(), the executable file is specified as a simple filename; the system searches for this file in the list of directories specified by PATH (in the same way as for execvp(3)). For the remainder of this page, the discussion is phrased in terms of posix_spawn(), with the understanding that posix_spawnp() differs only on the point just described.
The remaining arguments to these two functions are as follows:
Below, the functions are described in terms of a three-step process: the fork() step, the pre-exec() step (executed in the child), and the exec() step (executed in the child).
The PID of the new child process is placed in *pid. The posix_spawn() function then returns control to the parent process.
Subsequently, the parent can use one of the system calls described in wait(2) to check the status of the child process. If the child fails in any of the housekeeping steps described below, or fails to execute the desired file, it exits with a status of 127.
Before glibc 2.24, the child process is created using vfork(2) instead of fork(2) when either of the following is true:
In other words, vfork(2) is used if the caller requests it, or if there is no cleanup expected in the child before it exec(3)s the requested file.
All process attributes in the child, other than those affected by attributes specified in the object pointed to by attrp and the file actions in the object pointed to by file_actions, will be affected as though the child was created with fork(2) and it executed the program with execve(2).
The process attributes actions are defined by the attributes object pointed to by attrp. The spawn-flags attribute (set using posix_spawnattr_setflags(3)) controls the general actions that occur, and other attributes in the object specify values to be used during those actions.
The effects of the flags that may be specified in spawn-flags are as follows:
If the POSIX_SPAWN_SETSCHEDPARAM and POSIX_SPAWN_SETSCHEDPOLICY flags are not specified, the child inherits the corresponding scheduling attributes from the parent.
If attrp is NULL, then the default behaviors described above for each flag apply.
The file_actions argument specifies a sequence of file operations that are performed in the child process after the general processing described above, and before it performs the exec(3). If file_actions is NULL, then no special action is taken, and standard exec(3) semantics apply---file descriptors open before the exec remain open in the new process, except those for which the FD_CLOEXEC flag has been set. File locks remain in place.
If file_actions is not NULL, then it contains an ordered set of requests to open(2), close(2), and dup2(2) files. These requests are added to the file_actions by posix_spawn_file_actions_addopen(3), posix_spawn_file_actions_addclose(3), and posix_spawn_file_actions_adddup2(3). The requested operations are performed in the order they were added to file_actions.
If any of the housekeeping actions fails (due to bogus values being passed or other reasons why signal handling, process scheduling, process group ID functions, and file descriptor operations might fail), the child process exits with exit value 127.
The child process takes its environment from the envp argument, which is interpreted as if it had been passed to execve(2). The arguments to the created process come from the argv argument, which is processed as for execve(2).
Even when these functions return a success status, the child process may still fail for a plethora of reasons related to its pre-exec() initialization. In addition, the exec(3) may fail. In all of these cases, the child process will exit with the exit value of 127.
In addition, these functions fail if:
According to POSIX, it is unspecified whether fork handlers established with pthread_atfork(3) are called when posix_spawn() is invoked. Since glibc 2.24, the fork handlers are not executed in any case. On older implementations, fork handlers are called only if the child is created using fork(2).
There is no "posix_fspawn" function (i.e., a function that is to posix_spawn() as fexecve(3) is to execve(2)). However, this functionality can be obtained by specifying the path argument as one of the files in the caller's /proc/self/fd directory.
In the first run, the date(1) command is executed in the child, and the posix_spawn() call employs no file actions or attributes objects.
$ ./a.out date PID of child: 7634 Tue Feb 1 19:47:50 CEST 2011 Child status: exited, status=0
In the next run, the -c command-line option is used to create a file actions object that closes standard output in the child. Consequently, date(1) fails when trying to perform output and exits with a status of 1.
$ ./a.out -c date PID of child: 7636 date: write error: Bad file descriptor Child status: exited, status=1
In the next run, the -s command-line option is used to create an attributes object that specifies that all (blockable) signals in the child should be blocked. Consequently, trying to kill child with the default signal sent by kill(1) (i.e., SIGTERM) fails, because that signal is blocked. Therefore, to kill the child, SIGKILL is necessary (SIGKILL can't be blocked).
$ ./a.out -s sleep 60 & [1] 7637 $ PID of child: 7638
$ kill 7638 $ kill -KILL 7638 $ Child status: killed by signal 9 [1]+ Done ./a.out -s sleep 60
When we try to execute a nonexistent command in the child, the exec(3) fails and the child exits with a status of 127.
$ ./a.out xxxxx PID of child: 10190 Child status: exited, status=127
#define errExit(msg) do { perror(msg); \
exit(EXIT_FAILURE); } while (0)
#define errExitEN(en, msg) \
do { errno = en; perror(msg); \
exit(EXIT_FAILURE); } while (0)
char **environ;
int
main(int argc, char *argv[])
{
pid_t child_pid;
int s, opt, status;
sigset_t mask;
posix_spawnattr_t attr;
posix_spawnattr_t *attrp;
posix_spawn_file_actions_t file_actions;
posix_spawn_file_actions_t *file_actionsp;
/* Parse command-line options, which can be used to specify an
attributes object and file actions object for the child. */
attrp = NULL;
file_actionsp = NULL;
while ((opt = getopt(argc, argv, "sc")) != -1) {
switch (opt) {
case 'c': /* -c: close standard output in child */
/* Create a file actions object and add a "close"
action to it */
s = posix_spawn_file_actions_init(&file_actions);
if (s != 0)
errExitEN(s, "posix_spawn_file_actions_init");
s = posix_spawn_file_actions_addclose(&file_actions,
STDOUT_FILENO);
if (s != 0)
errExitEN(s, "posix_spawn_file_actions_addclose");
file_actionsp = &file_actions;
break;
case 's': /* -s: block all signals in child */
/* Create an attributes object and add a "set signal mask"
action to it */
s = posix_spawnattr_init(&attr);
if (s != 0)
errExitEN(s, "posix_spawnattr_init");
s = posix_spawnattr_setflags(&attr, POSIX_SPAWN_SETSIGMASK);
if (s != 0)
errExitEN(s, "posix_spawnattr_setflags");
sigfillset(&mask);
s = posix_spawnattr_setsigmask(&attr, &mask);
if (s != 0)
errExitEN(s, "posix_spawnattr_setsigmask");
attrp = &attr;
break;
}
}
/* Spawn the child. The name of the program to execute and the
command-line arguments are taken from the command-line arguments
of this program. The environment of the program execed in the
child is made the same as the parent's environment. */
s = posix_spawnp(&child_pid, argv[optind], file_actionsp, attrp,
&argv[optind], environ);
if (s != 0)
errExitEN(s, "posix_spawn");
/* Destroy any objects that we created earlier */
if (attrp != NULL) {
s = posix_spawnattr_destroy(attrp);
if (s != 0)
errExitEN(s, "posix_spawnattr_destroy");
}
if (file_actionsp != NULL) {
s = posix_spawn_file_actions_destroy(file_actionsp);
if (s != 0)
errExitEN(s, "posix_spawn_file_actions_destroy");
}
printf("PID of child: %jd\n", (intmax_t) child_pid);
/* Monitor status of the child until it terminates */
do {
s = waitpid(child_pid, &status, WUNTRACED | WCONTINUED);
if (s == -1)
errExit("waitpid");
printf("Child status: ");
if (WIFEXITED(status)) {
printf("exited, status=%d\n", WEXITSTATUS(status));
} else if (WIFSIGNALED(status)) {
printf("killed by signal %d\n", WTERMSIG(status));
} else if (WIFSTOPPED(status)) {
printf("stopped by signal %d\n", WSTOPSIG(status));
} else if (WIFCONTINUED(status)) {
printf("continued\n");
}
} while (!WIFEXITED(status) && !WIFSIGNALED(status));