posix_spawn(3)
๐ posix_spawn(3) โ the spawn-a-process situation ๐
okay bestie, gather round, because this one is from the Library Functions Manual and it's giving "let me make a whole new process for you" energy. no cap.
โจ NAME โจ
posix_spawn, posix_spawnp โ spawn a process ๐ฃ
๐ LIBRARY ๐
Standard C library (libc, -lc) โ the classic, the icon, the one you already link against.
๐ SYNOPSIS ๐
#include <spawn.h>
int posix_spawn(pid_t *restrict pid, const char *restrict path,
const posix_spawn_file_actions_t *restrict file_actions,
const posix_spawnattr_t *restrict attrp,
char *const argv[restrict],
char *const envp[restrict]);
int posix_spawnp(pid_t *restrict pid, const char *restrict file,
const posix_spawn_file_actions_t *restrict file_actions,
const posix_spawnattr_t *restrict attrp,
char *const argv[restrict],
char *const envp[restrict]);
๐ธ DESCRIPTION ๐ธ
so. posix_spawn() and posix_spawnp() are your "make a new child process that runs a specified file" girlies. ๐
POSIX literally specified these functions so there'd be a standardized way to create new processes on machines that can't handle the fork(2) system call at all. and who are those machines? generally the small ones โ embedded systems that are out here living without MMU support. iconic honestly.
what posix_spawn() and posix_spawnp() actually give you is the combined functionality of fork(2) plus exec(3), with some optional little housekeeping steps run in the child before the exec(3). but bestie, hear me: these functions are not meant to replace the fork(2) and execve(2) system calls. not even close. they only provide a subset of the functionality you can get by using those system calls directly. so don't come for them with expectations they never signed up for. ๐
the one and only difference between posix_spawn() and posix_spawnp() is how they name the file the child is gonna execute:
- with
posix_spawn(), the executable file is given as a pathname โ absolute or relative, either one works, you do you. - with
posix_spawnp(), the executable file is given as a simple filename, and the system goes searching for it through the list of directories inPATHโ exactly the same wayexecvp(3)does it. โจ
for the rest of this page, everything is written in terms of posix_spawn(), with the understanding that posix_spawnp() differs only on that one point just described. okay? okay. moving on. ๐ซถ
the remaining arguments to these two functions are as follows:
pidโ points to a buffer that gets used to return the process ID of the new child process. that's where the baby's PID goes. ๐file_actionsโ points to a spawn file actions object that specifies file-related actions to be performed in the child, in that little gap between thefork(2)andexec(3)steps. this object gets initialized and populated before theposix_spawn()call, usingposix_spawn_file_actions_init(3)and theposix_spawn_file_actions_*()functions.attrpโ points to an attributes object that specifies various attributes of the child process that's about to be created. this object also gets initialized and populated before theposix_spawn()call, usingposix_spawnattr_init(3)and theposix_spawnattr_*()functions.argv,envpโ specify the argument list and the environment for the program that gets executed in the child process, just like forexecve(2).
and below, all of this is described as a three-step process, because that's lowkey the cleanest way to see it: the fork() step, the pre-exec() step (which runs in the child), and the exec() step (which also runs in the child).
๐ the fork() step ๐
since glibc 2.24, posix_spawn() kicks things off by calling clone(2) with the CLONE_VM and CLONE_VFORK flags. older implementations use fork(2), or possibly vfork(2) โ more on that below, don't worry, we get there.
the PID of the new child process is placed in *pid. then posix_spawn() hands control right back to the parent process.
after that, the parent can use one of the system calls described in wait(2) to check the status of the child process. and if the child fails in any of the housekeeping steps described below, or fails to actually 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) whenever either of these is true:
- the spawn-flags element of the attributes object pointed to by
attrpcontains the GNU-specific flagPOSIX_SPAWN_USEVFORK; or file_actionsisNULL, and the spawn-flags element of the attributes object pointed to byattrpdoes not containPOSIX_SPAWN_SETSIGMASK,POSIX_SPAWN_SETSIGDEF,POSIX_SPAWN_SETSCHEDPARAM,POSIX_SPAWN_SETSCHEDULER,POSIX_SPAWN_SETPGROUP, orPOSIX_SPAWN_RESETIDS.
in other words: vfork(2) gets used if the caller asks for it, or if there's no cleanup expected in the child before it exec(3)s the requested file. simple as that. โจ
๐ the pre-exec() step: housekeeping ๐
so in between the fork() and the exec() steps, a child process might need to do a lil set of housekeeping actions. and posix_spawn() and posix_spawnp() support a small, well-defined set of system tasks the child can accomplish before it executes the executable file. ๐งน
these operations are controlled by:
- the attributes object pointed to by
attrp, and - the file actions object pointed to by
file_actions.
and in the child, all this processing happens in the following sequence:
- Process attribute actions: signal mask, signal default handlers, scheduling algorithm and parameters, process group, and effective user and group IDs are all changed as specified by the attributes object pointed to by
attrp. - File actions, as specified in the
file_actionsargument, get performed in the order that they were specified using calls to theposix_spawn_file_actions_add*()functions. - File descriptors with the
FD_CLOEXECflag set are closed.
every process attribute in the child โ other than the ones affected by attributes specified in the object pointed to by attrp, and other than the file actions in the object pointed to by file_actions โ will be affected exactly as though the child had been created with fork(2) and had executed the program with execve(2). no extra plot twists. ๐ฏ
the process attribute 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 the other attributes in the object specify the values used during those actions.
the effects of the flags you can put in spawn-flags go like this:
POSIX_SPAWN_SETSIGMASKโ set the signal mask to the signal set specified in the spawn-sigmask attribute of the object pointed to byattrp. if thePOSIX_SPAWN_SETSIGMASKflag is not set, then the child just inherits the parent's signal mask. generational inheritance, love that for them.POSIX_SPAWN_SETSIGDEFโ reset the disposition of all signals in the set specified in the spawn-sigdefault attribute of the object pointed to byattrp, back to the default. for how the dispositions of signals not specified in the spawn-sigdefault attribute get treated, or how things get treated whenPOSIX_SPAWN_SETSIGDEFisn't specified at all โ seeexecve(2).POSIX_SPAWN_SETSCHEDPARAMโ if this flag is set, and thePOSIX_SPAWN_SETSCHEDULERflag is not set, then set the scheduling parameters to the parameters specified in the spawn-schedparam attribute of the object pointed to byattrp.POSIX_SPAWN_SETSCHEDULERโ set the scheduling policy algorithm and parameters of the child, like this:- the scheduling policy gets set to the value specified in the spawn-schedpolicy attribute of the object pointed to by
attrp. - the scheduling parameters get set to the value specified in the spawn-schedparam attribute of the object pointed to by
attrp(but see BUGS โ don't say I didn't warn you ๐).
- the scheduling policy gets set to the value specified in the spawn-schedpolicy attribute of the object pointed to by
and if the POSIX_SPAWN_SETSCHEDPARAM and POSIX_SPAWN_SETSCHEDPOLICY flags are not specified, the child inherits the corresponding scheduling attributes from the parent.
POSIX_SPAWN_RESETIDSโ if this flag is set, reset the effective UID and GID to the real UID and GID of the parent process. if this flag is not set, the child retains the effective UID and GID of the parent. in either case, if the set-user-ID and set-group-ID permission bits are enabled on the executable file, their effect will override the setting of the effective UID and GID โ seeexecve(2). yes, that's the plot twist, yes it matters. ๐POSIX_SPAWN_SETPGROUPโ set the process group to the value specified in the spawn-pgroup attribute of the object pointed to byattrp. if the spawn-pgroup attribute has the value0, the child's process group ID gets made the same as its process ID. and if thePOSIX_SPAWN_SETPGROUPflag is not set, the child inherits the parent's process group ID.POSIX_SPAWN_USEVFORKโ since glibc 2.24, this flag has no effect. periodt. on older implementations, setting this flag forces thefork()step to usevfork(2)instead offork(2). and heads up: the_GNU_SOURCEfeature test macro must be defined to obtain the definition of this constant.POSIX_SPAWN_SETSID(since glibc 2.26) โ if this flag is set, the child process shall create a new session and become the session leader. the child process shall also become the process group leader of the new process group in the session (seesetsid(2)). main character energy fr fr. the_GNU_SOURCEfeature test macro must be defined to obtain the definition of this constant.
and if attrp is NULL? then the default behaviors described above for each flag apply. easy.
now the file_actions argument specifies a sequence of file operations that get 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 โ meaning file descriptors that were open before the exec remain open in the new process, except for those where the FD_CLOEXEC flag has been set. and 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 get 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). and the requested operations are performed in the order they were added to file_actions. no queue-jumping allowed bestie. ๐
โ ๏ธ and here's the part where you pay attention: if any of the housekeeping actions fails โ whether it's because bogus values got passed, or for 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 exec() step ๐ฆ
once the child has successfully forked and performed all the requested pre-exec steps, the child runs the requested executable. that's the whole goal. ๐
the child process takes its environment from the envp argument, which gets interpreted as if it had been passed to execve(2). and the arguments to the created process come from the argv argument, which is processed as for execve(2).
part 1 done bestie, take a sip of water because there's more coming ๐ง
๐ RETURN VALUE ๐
okay so when everything goes right, posix_spawn() and posix_spawnp() drop the child's PID into pid and hand you back a 0. slay. โจ
but bestie, if something goes wrong during the fork() step, it's giving nothing: no child gets created at all, the contents of *pid are just unspecified (translation: don't look at it, it means nothing), and the functions return an error number like the ones we're about to spill below.
and here's the thing that lowkey trips everyone up: even when these functions say "success," the child can still fail for a whole plethora of reasons tied to its pre-exec()initialization. plus theexec(3)itself might fail. in all of those cases? the child process exits with the exit value of127. that's the vibe check. ๐
๐ญ ERRORS ๐ญ
so posix_spawn() and posix_spawnp() only fail in the case where the underlying fork(2), vfork(2), or clone(2) call fails. in those cases, they return an error number โ one of the errors described for fork(2), vfork(2), or clone(2). inherited drama, basically.
and also, these functions fail if:
ENOSYSโ Function not supported on this system. literally not this system's moment. ๐
๐ STANDARDS ๐
- POSIX.1-2008. periodt.
๐ธ HISTORY ๐ธ
- glibc 2.2. she's an icon, she's a legend.
- POSIX.1-2001. the origin story.
โจ NOTES โจ
the housekeeping activities in the child are controlled by the objects pointed to by attrp (for non-file actions) and file_actions. in POSIX parlance, the posix_spawnattr_t and posix_spawn_file_actions_t data types are referred to as objects, and their elements are not specified by name. so if you write portable programs, initialize these objects using only the POSIX-specified functions. ๐ซถ
in other words: even though these objects may be implemented as structures containing fields, portable programs must avoid dependence on such implementation details. don't go peeking under the hood, bestie, it's not for you. ๐
according to POSIX, it's unspecified whether fork handlers established with pthread_atfork(3) are called when posix_spawn() is invoked. and 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). iykyk.
there is no posix_fspawn function (i.e., a function that is to posix_spawn() as fexecve(3) is to execve(2)). ๐ญ but โ plot twist โ you can get this functionality by specifying the path argument as one of the files in the caller's /proc/self/fd directory. workaround queen. ๐
๐ BUGS ๐
POSIX.1 says that when POSIX_SPAWN_SETSCHEDULER is specified in spawn-flags, then the POSIX_SPAWN_SETSCHEDPARAM (if present) is ignored. however โ before glibc 2.14 โ calls to posix_spawn() failed with an error if POSIX_SPAWN_SETSCHEDULER was specified without also specifying POSIX_SPAWN_SETSCHEDPARAM. old glibc was doing the most, honestly. ๐
๐ EXAMPLES ๐
okay showtime. the program below demonstrates the use of various functions in the POSIX spawn API. the program accepts command-line attributes that can be used to create file actions and attributes objects. the remaining command-line arguments are used as the executable name and command-line arguments of the program that is executed in the child. so basically it's a little wrapper and she ate. ๐
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. no output for you, bestie. ๐
$ ./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). it's giving immovable object energy. ๐ฅ
$ ./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. (told you about that 127 earlier, no cap.)
$ ./a.out xxxxx;
PID of child: 10190
Child status: exited, status=127
๐ธ Program source ๐ธ
#include <err.h>
#include <errno.h>
#include <spawn.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <wait.h>
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)
errc(EXIT_FAILURE, s, "posix_spawn_file_actions_init");
s = posix_spawn_file_actions_addclose(&file_actions,
STDOUT_FILENO);
if (s != 0)
errc(EXIT_FAILURE, 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)
errc(EXIT_FAILURE, s, "posix_spawnattr_init");
s = posix_spawnattr_setflags(&attr, POSIX_SPAWN_SETSIGMASK);
if (s != 0)
errc(EXIT_FAILURE, s, "posix_spawnattr_setflags");
sigfillset(&mask);
s = posix_spawnattr_setsigmask(&attr, &mask);
if (s != 0)
errc(EXIT_FAILURE, s, "posix_spawnattr_setsigmask");
attrp = &attr;
break;
}
}
if (argv[optind] == NULL) {
fprintf(stderr, "Usage: %s [-cs] executable [args]\n", argv[0]);
exit(EXIT_FAILURE);
}
/* 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)
errc(EXIT_FAILURE, s, "posix_spawn");
/* Destroy any objects that we created earlier. */
if (attrp != NULL) {
s = posix_spawnattr_destroy(attrp);
if (s != 0)
errc(EXIT_FAILURE, s, "posix_spawnattr_destroy");
}
if (file_actionsp != NULL) {
s = posix_spawn_file_actions_destroy(file_actionsp);
if (s != 0)
errc(EXIT_FAILURE, 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)
err(EXIT_FAILURE, "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));
exit(EXIT_SUCCESS);
}
๐ฆ SEE ALSO ๐ฆ
close(2), dup2(2), execl(2), execlp(2), fork(2), open(2), sched_setparam(2), sched_setscheduler(2), setpgid(2), setuid(2), sigaction(2), sigprocmask(2), posix_spawn_file_actions_addclose(3), posix_spawn_file_actions_adddup2(3), posix_spawn_file_actions_addopen(3), posix_spawn_file_actions_destroy(3), posix_spawn_file_actions_init(3), posix_spawnattr_destroy(3), posix_spawnattr_getflags(3), posix_spawnattr_getpgroup(3), posix_spawnattr_getschedparam(3), posix_spawnattr_getschedpolicy(3), posix_spawnattr_getsigdefault(3), posix_spawnattr_getsigmask(3), posix_spawnattr_init(3), posix_spawnattr_setflags(3), posix_spawnattr_setpgroup(3), posix_spawnattr_setschedparam(3), posix_spawnattr_setschedpolicy(3), posix_spawnattr_setsigdefault(3), posix_spawnattr_setsigmask(3), pthread_atfork(3), <spawn.h>, Base Definitions volume of POSIX.1-2001, http://www.opengroup.org/unix/online.html
aaand that's the whole page bestie, you made it to the end ๐ซถ this one's from Linux man-pages 6.20, dated 2026-02-08, and queen posix_spawn(3) truly served. go spawn something cute, mwah ๐
โจ
๐ฆ where this page comes from
- arch rolling: man-pages 6.20-1 ยท BSD-2-Clause AND BSD-3-Clause AND BSD-4.3TAHOE AND BSD-4-Clause-UC AND GPL-1.0-or-later AND GPL-2.0-only AND GPL-2.0-or-later AND GPL-3.0-or-later AND LGPL-3.0-linking-exception AND LGPL-3.0-or-later AND LicenseRef-Public-Domain AND LicenseRef-UltraPermissive AND Linux-man-pages-1-para AND Linux-man-pages-copyleft AND Linux-man-pages-copyleft-2-para AND Linux-man-pages-copyleft-var AND MIT AND Spencer-94
- nixpkgs unstable: man-pages 6.20
- ๐ the page's license: Linux-man-pages-copyleft
- Copyright 2010, Michael Kerrisk <mtk.manpages@gmail.com>
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms