1POSIX_SPAWN(3)             Linux Programmer's Manual            POSIX_SPAWN(3)
2
3
4

NAME

6       posix_spawn, posix_spawnp - spawn a process
7

SYNOPSIS

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

DESCRIPTION

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

RETURN VALUE

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

ERRORS

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

VERSIONS

255       The posix_spawn() and  posix_spawnp()  functions  are  available  since
256       glibc 2.2.
257

CONFORMING TO

259       POSIX.1-2001, POSIX.1-2008.
260

NOTES

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

BUGS

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

EXAMPLES

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

SEE ALSO

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

COLOPHON

480       This page is part of release 5.07 of the Linux man-pages project.  A
481       description of the project, information about reporting bugs, and the
482       latest version of this page, can be found at
483       https://www.kernel.org/doc/man-pages/.
484
485
486
487GNU                               2020-04-11                    POSIX_SPAWN(3)
Impressum