1posix_spawn(3)             Library Functions Manual             posix_spawn(3)
2
3
4

NAME

6       posix_spawn, posix_spawnp - spawn a process
7

LIBRARY

9       Standard C library (libc, -lc)
10

SYNOPSIS

12       #include <spawn.h>
13
14       int posix_spawn(pid_t *restrict pid, const char *restrict path,
15                       const posix_spawn_file_actions_t *restrict file_actions,
16                       const posix_spawnattr_t *restrict attrp,
17                       char *const argv[restrict],
18                       char *const envp[restrict]);
19       int posix_spawnp(pid_t *restrict pid, const char *restrict file,
20                       const posix_spawn_file_actions_t *restrict file_actions,
21                       const posix_spawnattr_t *restrict attrp,
22                       char *const argv[restrict],
23                       char *const envp[restrict]);
24

DESCRIPTION

26       The posix_spawn() and posix_spawnp() functions are used to create a new
27       child process that executes a specified  file.   These  functions  were
28       specified  by  POSIX  to  provide a standardized method of creating new
29       processes on machines that lack the capability to support  the  fork(2)
30       system  call.   These  machines  are  generally small, embedded systems
31       lacking MMU support.
32
33       The posix_spawn() and posix_spawnp() functions provide the  functional‐
34       ity  of a combined fork(2) and exec(3), with some optional housekeeping
35       steps in the child process before the exec(3).  These functions are not
36       meant to replace the fork(2) and execve(2) system calls.  In fact, they
37       provide only a subset of the functionality that can be achieved by  us‐
38       ing the system calls.
39
40       The  only  difference  between  posix_spawn() and posix_spawnp() is the
41       manner in which they specify the file  to  be  executed  by  the  child
42       process.   With  posix_spawn(),  the  executable file is specified as a
43       pathname (which can be absolute or relative).  With posix_spawnp(), the
44       executable  file is specified as a simple filename; the system searches
45       for this file in the list of directories specified by PATH (in the same
46       way  as for execvp(3)).  For the remainder of this page, the discussion
47       is phrased in terms  of  posix_spawn(),  with  the  understanding  that
48       posix_spawnp() differs only on the point just described.
49
50       The remaining arguments to these two functions are as follows:
51
52       pid    points  to a buffer that is used to return the process ID of the
53              new child process.
54
55       file_actions
56              points to a spawn file actions object  that  specifies  file-re‐
57              lated  actions  to be performed in the child between the fork(2)
58              and exec(3) steps.  This object is initialized and populated be‐
59              fore   the   posix_spawn()   call   using   posix_spawn_file_ac‐
60              tions_init(3) and the posix_spawn_file_actions_*() functions.
61
62       attrp  points to an  attributes  objects  that  specifies  various  at‐
63              tributes  of the created child process.  This object is initial‐
64              ized  and  populated  before  the   posix_spawn()   call   using
65              posix_spawnattr_init(3) and the posix_spawnattr_*() functions.
66
67       argv
68       envp   specify  the  argument list and environment for the program that
69              is executed in the child process, as for execve(2).
70
71       Below, the functions are described in terms of  a  three-step  process:
72       the  fork()  step, the pre-exec() step (executed in the child), and the
73       exec() step (executed in the child).
74
75   fork() step
76       Since glibc 2.24,  the  posix_spawn()  function  commences  by  calling
77       clone(2)  with  CLONE_VM  and CLONE_VFORK flags.  Older implementations
78       use fork(2), or possibly vfork(2) (see below).
79
80       The PID of the new child process is placed in *pid.  The  posix_spawn()
81       function then returns control to the parent process.
82
83       Subsequently,  the  parent can use one of the system calls described in
84       wait(2) to check the status of the child process.  If the  child  fails
85       in  any  of the housekeeping steps described below, or fails to execute
86       the desired file, it exits with a status of 127.
87
88       Before glibc 2.24, the child process is created using vfork(2)  instead
89       of fork(2) when either of the following is true:
90
91       •  the spawn-flags element of the attributes object pointed to by attrp
92          contains the GNU-specific flag POSIX_SPAWN_USEVFORK; or
93
94file_actions is NULL and the spawn-flags element of  the  attributes
95          object  pointed to by attrp does not contain POSIX_SPAWN_SETSIGMASK,
96          POSIX_SPAWN_SETSIGDEF,                    POSIX_SPAWN_SETSCHEDPARAM,
97          POSIX_SPAWN_SETSCHEDULER,  POSIX_SPAWN_SETPGROUP, or POSIX_SPAWN_RE‐
98          SETIDS.
99
100       In other words, vfork(2) is used if the caller requests it, or if there
101       is  no  cleanup  expected in the child before it exec(3)s the requested
102       file.
103
104   pre-exec() step: housekeeping
105       In between the fork() and the exec() steps, a child process may need to
106       perform   a   set  of  housekeeping  actions.   The  posix_spawn()  and
107       posix_spawnp() functions support a small, well-defined  set  of  system
108       tasks that the child process can accomplish before it executes the exe‐
109       cutable file.  These operations are controlled by the attributes object
110       pointed  to by attrp and the file actions object pointed to by file_ac‐
111       tions.  In the child, processing is done in the following sequence:
112
113       (1)  Process attribute actions: signal mask, signal  default  handlers,
114            scheduling  algorithm and parameters, process group, and effective
115            user and group IDs are changed as specified by the attributes  ob‐
116            ject pointed to by attrp.
117
118       (2)  File  actions, as specified in the file_actions argument, are per‐
119            formed in the order that they were specified using  calls  to  the
120            posix_spawn_file_actions_add*() functions.
121
122       (3)  File descriptors with the FD_CLOEXEC flag set are closed.
123
124       All  process  attributes in the child, other than those affected by at‐
125       tributes specified in the object pointed to by attrp and the  file  ac‐
126       tions  in  the  object  pointed to by file_actions, will be affected as
127       though the child was created with fork(2) and it executed  the  program
128       with execve(2).
129
130       The  process  attributes  actions  are defined by the attributes object
131       pointed to by attrp.  The spawn-flags attribute (set using  posix_spaw‐
132       nattr_setflags(3))  controls  the general actions that occur, and other
133       attributes in the object specify values to be  used  during  those  ac‐
134       tions.
135
136       The  effects  of  the flags that may be specified in spawn-flags are as
137       follows:
138
139       POSIX_SPAWN_SETSIGMASK
140              Set the signal mask to the signal set specified  in  the  spawn-
141              sigmask  attribute  of  the  object pointed to by attrp.  If the
142              POSIX_SPAWN_SETSIGMASK flag is not set, then the child  inherits
143              the parent's signal mask.
144
145       POSIX_SPAWN_SETSIGDEF
146              Reset the disposition of all signals in the set specified in the
147              spawn-sigdefault attribute of the object pointed to by attrp  to
148              the  default.   For the treatment of the dispositions of signals
149              not specified in the spawn-sigdefault attribute, or  the  treat‐
150              ment when POSIX_SPAWN_SETSIGDEF is not specified, see execve(2).
151
152       POSIX_SPAWN_SETSCHEDPARAM
153              If  this  flag  is set, and the POSIX_SPAWN_SETSCHEDULER flag is
154              not set, then set the scheduling parameters  to  the  parameters
155              specified  in  the  spawn-schedparam  attribute  of  the  object
156              pointed to by attrp.
157
158       POSIX_SPAWN_SETSCHEDULER
159              Set the scheduling policy algorithm and parameters of the child,
160              as follows:
161
162              •  The  scheduling  policy  is set to the value specified in the
163                 spawn-schedpolicy attribute of the object pointed to  by  at‐
164                 trp.
165
166              •  The  scheduling  parameters are set to the value specified in
167                 the spawn-schedparam attribute of the object  pointed  to  by
168                 attrp (but see BUGS).
169
170              If  the POSIX_SPAWN_SETSCHEDPARAM and POSIX_SPAWN_SETSCHEDPOLICY
171              flags are not specified, the child  inherits  the  corresponding
172              scheduling attributes from the parent.
173
174       POSIX_SPAWN_RESETIDS
175              If this flag is set, reset the effective UID and GID to the real
176              UID and GID of the parent process.  If this  flag  is  not  set,
177              then  the child retains the effective UID and GID of the parent.
178              In either case, if the set-user-ID and  set-group-ID  permission
179              bits are enabled on the executable file, their effect will over‐
180              ride the setting of the effective UID and GID (se execve(2)).
181
182       POSIX_SPAWN_SETPGROUP
183              Set the process group to the value specified in the spawn-pgroup
184              attribute  of  the  object  pointed  to by attrp.  If the spawn-
185              pgroup attribute has the value 0, the child's process  group  ID
186              is  made  the  same as its process ID.  If the POSIX_SPAWN_SETP‐
187              GROUP flag is not set, the child inherits the  parent's  process
188              group ID.
189
190       POSIX_SPAWN_USEVFORK
191              Since glibc 2.24, this flag has no effect.  On older implementa‐
192              tions, setting this flag forces the fork() step to use  vfork(2)
193              instead  of fork(2).  The _GNU_SOURCE feature test macro must be
194              defined to obtain the definition of this constant.
195
196       POSIX_SPAWN_SETSID (since glibc 2.26)
197              If this flag is set, the child process shall create a  new  ses‐
198              sion  and  become  the  session leader.  The child process shall
199              also become the process group leader of the new process group in
200              the session (see setsid(2)).  The _GNU_SOURCE feature test macro
201              must be defined to obtain the definition of this constant.
202
203       If attrp is NULL, then the default behaviors described above  for  each
204       flag apply.
205
206       The  file_actions argument specifies a sequence of file operations that
207       are performed in the child process after  the  general  processing  de‐
208       scribed  above, and before it performs the exec(3).  If file_actions is
209       NULL, then no special action is taken, and standard  exec(3)  semantics
210       apply—file  descriptors  open  before  the  exec remain open in the new
211       process, except those for which the FD_CLOEXEC flag has been set.  File
212       locks remain in place.
213
214       If  file_actions  is  not  NULL, then it contains an ordered set of re‐
215       quests to open(2), close(2), and dup2(2)  files.   These  requests  are
216       added   to  the  file_actions  by  posix_spawn_file_actions_addopen(3),
217       posix_spawn_file_actions_addclose(3), and  posix_spawn_file_actions_ad‐
218       ddup2(3).   The  requested  operations  are performed in the order they
219       were added to file_actions.
220
221       If any of the housekeeping actions fails (due  to  bogus  values  being
222       passed  or  other  reasons  why  signal  handling,  process scheduling,
223       process group ID functions, and file descriptor operations might fail),
224       the child process exits with exit value 127.
225
226   exec() step
227       Once the child has successfully forked and performed all requested pre-
228       exec steps, the child runs the requested executable.
229
230       The child process takes its environment from the envp  argument,  which
231       is interpreted as if it had been passed to execve(2).  The arguments to
232       the created process come from the argv argument, which is processed  as
233       for execve(2).
234

RETURN VALUE

236       Upon  successful completion, posix_spawn() and posix_spawnp() place the
237       PID of the child process in pid, and return 0.  If there  is  an  error
238       during  the fork() step, then no child is created, the contents of *pid
239       are unspecified, and these functions return  an  error  number  as  de‐
240       scribed below.
241
242       Even  when  these  functions return a success status, the child process
243       may still fail for a plethora of reasons related to its pre-exec() ini‐
244       tialization.   In  addition,  the  exec(3)  may  fail.  In all of these
245       cases, the child process will exit with the exit value of 127.
246

ERRORS

248       The posix_spawn() and posix_spawnp() functions fail only  in  the  case
249       where  the  underlying  fork(2),  vfork(2), or clone(2) call fails;  in
250       these cases, these functions return an error number, which will be  one
251       of the errors described for fork(2), vfork(2), or clone(2).
252
253       In addition, these functions fail if:
254
255       ENOSYS Function not supported on this system.
256

STANDARDS

258       POSIX.1-2008.
259

HISTORY

261       glibc 2.2.  POSIX.1-2001.
262

NOTES

264       The  housekeeping activities in the child are controlled by the objects
265       pointed to by attrp (for non-file actions) and  file_actions  In  POSIX
266       parlance,  the  posix_spawnattr_t  and  posix_spawn_file_actions_t data
267       types are referred to as objects, and their elements are not  specified
268       by  name.  Portable programs should initialize these objects using only
269       the POSIX-specified functions.  (In other words, although these objects
270       may  be  implemented as structures containing fields, portable programs
271       must avoid dependence on such implementation details.)
272
273       According to POSIX, it is unspecified whether fork handlers established
274       with pthread_atfork(3) are called when posix_spawn() is invoked.  Since
275       glibc 2.24, the fork handlers are not executed in any case.   On  older
276       implementations,  fork handlers are called only if the child is created
277       using fork(2).
278
279       There is no "posix_fspawn"  function  (i.e.,  a  function  that  is  to
280       posix_spawn()  as fexecve(3) is to execve(2)).  However, this function‐
281       ality can be obtained by specifying the path argument  as  one  of  the
282       files in the caller's /proc/self/fd directory.
283

BUGS

285       POSIX.1  says that when POSIX_SPAWN_SETSCHEDULER is specified in spawn-
286       flags, then the  POSIX_SPAWN_SETSCHEDPARAM  (if  present)  is  ignored.
287       However, before glibc 2.14, calls to posix_spawn() failed with an error
288       if  POSIX_SPAWN_SETSCHEDULER  was  specified  without  also  specifying
289       POSIX_SPAWN_SETSCHEDPARAM.
290

EXAMPLES

292       The  program  below  demonstrates  the  use of various functions in the
293       POSIX spawn API.  The program accepts command-line attributes that  can
294       be  used  to create file actions and attributes objects.  The remaining
295       command-line arguments are used as the executable name and command-line
296       arguments of the program that is executed in the child.
297
298       In the first run, the date(1) command is executed in the child, and the
299       posix_spawn() call employs no file actions or attributes objects.
300
301           $ ./a.out date
302           PID of child: 7634
303           Tue Feb  1 19:47:50 CEST 2011
304           Child status: exited, status=0
305
306       In the next run, the -c command-line option is used to  create  a  file
307       actions object that closes standard output in the child.  Consequently,
308       date(1) fails when trying to perform output and exits with a status  of
309       1.
310
311           $ ./a.out -c date
312           PID of child: 7636
313           date: write error: Bad file descriptor
314           Child status: exited, status=1
315
316       In  the  next  run, the -s command-line option is used to create an at‐
317       tributes object that specifies that  all  (blockable)  signals  in  the
318       child  should  be blocked.  Consequently, trying to kill child with the
319       default signal sent by kill(1) (i.e., SIGTERM) fails, because that sig‐
320       nal  is  blocked.   Therefore,  to kill the child, SIGKILL is necessary
321       (SIGKILL can't be blocked).
322
323           $ ./a.out -s sleep 60 &
324           [1] 7637
325           $ PID of child: 7638
326
327           $ kill 7638
328           $ kill -KILL 7638
329           $ Child status: killed by signal 9
330           [1]+  Done                    ./a.out -s sleep 60
331
332       When we try to execute a nonexistent command in the child, the  exec(3)
333       fails and the child exits with a status of 127.
334
335           $ ./a.out xxxxx
336           PID of child: 10190
337           Child status: exited, status=127
338
339   Program source
340
341       #include <errno.h>
342       #include <spawn.h>
343       #include <stdint.h>
344       #include <stdio.h>
345       #include <stdlib.h>
346       #include <string.h>
347       #include <unistd.h>
348       #include <wait.h>
349
350       #define errExit(msg)    do { perror(msg); \
351                                    exit(EXIT_FAILURE); } while (0)
352
353       #define errExitEN(en, msg) \
354                               do { errno = en; perror(msg); \
355                                    exit(EXIT_FAILURE); } while (0)
356
357       char **environ;
358
359       int
360       main(int argc, char *argv[])
361       {
362           pid_t child_pid;
363           int s, opt, status;
364           sigset_t mask;
365           posix_spawnattr_t attr;
366           posix_spawnattr_t *attrp;
367           posix_spawn_file_actions_t file_actions;
368           posix_spawn_file_actions_t *file_actionsp;
369
370           /* Parse command-line options, which can be used to specify an
371              attributes object and file actions object for the child. */
372
373           attrp = NULL;
374           file_actionsp = NULL;
375
376           while ((opt = getopt(argc, argv, "sc")) != -1) {
377               switch (opt) {
378               case 'c':       /* -c: close standard output in child */
379
380                   /* Create a file actions object and add a "close"
381                      action to it. */
382
383                   s = posix_spawn_file_actions_init(&file_actions);
384                   if (s != 0)
385                       errExitEN(s, "posix_spawn_file_actions_init");
386
387                   s = posix_spawn_file_actions_addclose(&file_actions,
388                                                         STDOUT_FILENO);
389                   if (s != 0)
390                       errExitEN(s, "posix_spawn_file_actions_addclose");
391
392                   file_actionsp = &file_actions;
393                   break;
394
395               case 's':       /* -s: block all signals in child */
396
397                   /* Create an attributes object and add a "set signal mask"
398                      action to it. */
399
400                   s = posix_spawnattr_init(&attr);
401                   if (s != 0)
402                       errExitEN(s, "posix_spawnattr_init");
403                   s = posix_spawnattr_setflags(&attr, POSIX_SPAWN_SETSIGMASK);
404                   if (s != 0)
405                       errExitEN(s, "posix_spawnattr_setflags");
406
407                   sigfillset(&mask);
408                   s = posix_spawnattr_setsigmask(&attr, &mask);
409                   if (s != 0)
410                       errExitEN(s, "posix_spawnattr_setsigmask");
411
412                   attrp = &attr;
413                   break;
414               }
415           }
416
417           /* Spawn the child. The name of the program to execute and the
418              command-line arguments are taken from the command-line arguments
419              of this program. The environment of the program execed in the
420              child is made the same as the parent's environment. */
421
422           s = posix_spawnp(&child_pid, argv[optind], file_actionsp, attrp,
423                            &argv[optind], environ);
424           if (s != 0)
425               errExitEN(s, "posix_spawn");
426
427           /* Destroy any objects that we created earlier. */
428
429           if (attrp != NULL) {
430               s = posix_spawnattr_destroy(attrp);
431               if (s != 0)
432                   errExitEN(s, "posix_spawnattr_destroy");
433           }
434
435           if (file_actionsp != NULL) {
436               s = posix_spawn_file_actions_destroy(file_actionsp);
437               if (s != 0)
438                   errExitEN(s, "posix_spawn_file_actions_destroy");
439           }
440
441           printf("PID of child: %jd\n", (intmax_t) child_pid);
442
443           /* Monitor status of the child until it terminates. */
444
445           do {
446               s = waitpid(child_pid, &status, WUNTRACED | WCONTINUED);
447               if (s == -1)
448                   errExit("waitpid");
449
450               printf("Child status: ");
451               if (WIFEXITED(status)) {
452                   printf("exited, status=%d\n", WEXITSTATUS(status));
453               } else if (WIFSIGNALED(status)) {
454                   printf("killed by signal %d\n", WTERMSIG(status));
455               } else if (WIFSTOPPED(status)) {
456                   printf("stopped by signal %d\n", WSTOPSIG(status));
457               } else if (WIFCONTINUED(status)) {
458                   printf("continued\n");
459               }
460           } while (!WIFEXITED(status) && !WIFSIGNALED(status));
461
462           exit(EXIT_SUCCESS);
463       }
464

SEE ALSO

466       close(2), dup2(2), execl(2), execlp(2), fork(2), open(2),
467       sched_setparam(2), sched_setscheduler(2), setpgid(2), setuid(2),
468       sigaction(2), sigprocmask(2), posix_spawn_file_actions_addclose(3),
469       posix_spawn_file_actions_adddup2(3),
470       posix_spawn_file_actions_addopen(3),
471       posix_spawn_file_actions_destroy(3), posix_spawn_file_actions_init(3),
472       posix_spawnattr_destroy(3), posix_spawnattr_getflags(3),
473       posix_spawnattr_getpgroup(3), posix_spawnattr_getschedparam(3),
474       posix_spawnattr_getschedpolicy(3), posix_spawnattr_getsigdefault(3),
475       posix_spawnattr_getsigmask(3), posix_spawnattr_init(3),
476       posix_spawnattr_setflags(3), posix_spawnattr_setpgroup(3),
477       posix_spawnattr_setschedparam(3), posix_spawnattr_setschedpolicy(3),
478       posix_spawnattr_setsigdefault(3), posix_spawnattr_setsigmask(3),
479       pthread_atfork(3), <spawn.h>, Base Definitions volume of POSIX.1-2001,
480       http://www.opengroup.org/unix/online.html
481
482
483
484Linux man-pages 6.04              2023-03-30                    posix_spawn(3)
Impressum