1EXEC(3P)                   POSIX Programmer's Manual                  EXEC(3P)
2
3
4

PROLOG

6       This  manual  page is part of the POSIX Programmer's Manual.  The Linux
7       implementation of this interface may differ (consult the  corresponding
8       Linux  manual page for details of Linux behavior), or the interface may
9       not be implemented on Linux.
10
11

NAME

13       environ, execl, execle, execlp, execv, execve, execvp, fexecve  —  exe‐
14       cute a file
15

SYNOPSIS

17       #include <unistd.h>
18
19       extern char **environ;
20       int execl(const char *path, const char *arg0, ... /*, (char *)0 */);
21       int execle(const char *path, const char *arg0, ... /*,
22           (char *)0, char *const envp[]*/);
23       int execlp(const char *file, const char *arg0, ... /*, (char *)0 */);
24       int execv(const char *path, char *const argv[]);
25       int execve(const char *path, char *const argv[], char *const envp[]);
26       int execvp(const char *file, char *const argv[]);
27       int fexecve(int fd, char *const argv[], char *const envp[]);
28

DESCRIPTION

30       The  exec  family  of functions shall replace the current process image
31       with a new process image. The new image shall  be  constructed  from  a
32       regular,  executable  file  called  the  new process image file.  There
33       shall be no return from a successful exec, because the calling  process
34       image is overlaid by the new process image.
35
36       The  fexecve()  function  shall  be equivalent to the execve() function
37       except that the file to be executed is determined by the file  descrip‐
38       tor fd instead of a pathname. The file offset of fd is ignored.
39
40       When  a  C-language program is executed as a result of a call to one of
41       the exec family of functions, it shall be entered as a C-language func‐
42       tion call as follows:
43
44           int main (int argc, char *argv[]);
45
46       where  argc  is  the  argument  count and argv is an array of character
47       pointers to the arguments themselves.  In addition, the following vari‐
48       able, which must be declared by the user if it is to be used directly:
49
50           extern char **environ;
51
52       is  initialized  as  a pointer to an array of character pointers to the
53       environment strings. The argv and environ arrays are each terminated by
54       a  null  pointer.  The  null  pointer terminating the argv array is not
55       counted in argc.
56
57       Applications can change the entire environment in a single operation by
58       assigning the environ variable to point to an array of character point‐
59       ers to the new environment strings. After assigning a new value to env‐
60       iron,  applications  should  not  rely  on  the new environment strings
61       remaining part of the environment, as a  call  to  getenv(),  putenv(),
62       setenv(),  unsetenv(), or any function that is dependent on an environ‐
63       ment variable may, on noticing that environ has changed, copy the envi‐
64       ronment strings to a new array and assign environ to point to it.
65
66       Any  application that directly modifies the pointers to which the envi‐
67       ron variable points has undefined behavior.
68
69       Conforming multi-threaded applications shall not use the environ  vari‐
70       able  to  access  or  modify  any  environment variable while any other
71       thread is concurrently modifying any environment variable.  A  call  to
72       any  function dependent on any environment variable shall be considered
73       a use of the environ variable to access that environment variable.
74
75       The arguments specified by a program with one  of  the  exec  functions
76       shall be passed on to the new process image in the corresponding main()
77       arguments.
78
79       The argument path points to a pathname that identifies the new  process
80       image file.
81
82       The  argument  file is used to construct a pathname that identifies the
83       new process image file. If the file argument contains a <slash> charac‐
84       ter,  the  file  argument  shall be used as the pathname for this file.
85       Otherwise, the path prefix for this file is obtained by a search of the
86       directories passed as the environment variable PATH (see the Base Defi‐
87       nitions volume of POSIX.1‐2008, Chapter 8, Environment Variables).   If
88       this environment variable is not present, the results of the search are
89       implementation-defined.
90
91       There are two distinct ways in which the contents of the process  image
92       file  may  cause the execution to fail, distinguished by the setting of
93       errno to either [ENOEXEC] or [EINVAL] (see the ERRORS section). In  the
94       cases  where  the  other  members of the exec family of functions would
95       fail and set errno to [ENOEXEC], the execlp()  and  execvp()  functions
96       shall execute a command interpreter and the environment of the executed
97       command shall be as if the process invoked the sh utility using execl()
98       as follows:
99
100           execl(<shell path>, arg0, file, arg1, ..., (char *)0);
101
102       where  <shell path> is an unspecified pathname for the sh utility, file
103       is the process image file, and for execvp(), where arg0, arg1,  and  so
104       on correspond to the values passed to execvp() in argv[0], argv[1], and
105       so on.
106
107       The arguments represented by arg0,...  are pointers to  null-terminated
108       character  strings.  These  strings  shall constitute the argument list
109       available to the new process image. The list is terminated  by  a  null
110       pointer.  The  argument  arg0 should point to a filename string that is
111       associated with the process being started by one of the exec functions.
112
113       The argument argv is an array of character pointers to  null-terminated
114       strings.  The  application  shall  ensure  that the last member of this
115       array is a null pointer. These strings shall  constitute  the  argument
116       list  available  to  the new process image. The value in argv[0] should
117       point to a filename string that is associated with  the  process  being
118       started by one of the exec functions.
119
120       The  argument envp is an array of character pointers to null-terminated
121       strings. These strings shall constitute the  environment  for  the  new
122       process image.  The envp array is terminated by a null pointer.
123
124       For  those forms not containing an envp pointer (execl(), execv(), exe‐
125       clp(), and execvp()), the environment for the new process  image  shall
126       be taken from the external variable environ in the calling process.
127
128       The  number  of  bytes available for the new process' combined argument
129       and environment  lists  is  {ARG_MAX}.   It  is  implementation-defined
130       whether  null  terminators,  pointers,  and/or  any alignment bytes are
131       included in this total.
132
133       File descriptors open in the calling process image shall remain open in
134       the  new  process  image,  except  for  those  whose close-on-exec flag
135       FD_CLOEXEC is set.  For those file descriptors that  remain  open,  all
136       attributes  of the open file description remain unchanged. For any file
137       descriptor that is closed for this reason, file locks are removed as  a
138       result  of  the  close  as  described  in  close().  Locks that are not
139       removed by closing of file descriptors remain unchanged.
140
141       If file descriptor 0, 1, or 2 would otherwise be closed  after  a  suc‐
142       cessful  call  to  one of the exec family of functions, implementations
143       may open an unspecified file for the file descriptor in the new process
144       image.  If  a  standard utility or a conforming application is executed
145       with file descriptor 0 not open for reading or with file  descriptor  1
146       or  2  not  open  for  writing, the environment in which the utility or
147       application is executed shall  be  deemed  non-conforming,  and  conse‐
148       quently  the  utility  or  application might not behave as described in
149       this standard.
150
151       Directory streams open in the calling process image shall be closed  in
152       the new process image.
153
154       The  state  of  the floating-point environment in the initial thread of
155       the new process image shall be set to the default.
156
157       The state of conversion descriptors and message catalog descriptors  in
158       the new process image is undefined.
159
160       For the new process image, the equivalent of:
161
162           setlocale(LC_ALL, "C")
163
164       shall be executed at start-up.
165
166       Signals  set  to  the  default  action (SIG_DFL) in the calling process
167       image shall be set to the default action  in  the  new  process  image.
168       Except  for SIGCHLD, signals set to be ignored (SIG_IGN) by the calling
169       process image shall be set to be ignored by the new process image. Sig‐
170       nals  set to be caught by the calling process image shall be set to the
171       default action in the new process image (see <signal.h>).
172
173       If the SIGCHLD signal is set to  be  ignored  by  the  calling  process
174       image,  it  is  unspecified  whether  the  SIGCHLD  signal is set to be
175       ignored or to the default action in the new process image.
176
177       After a successful call to any of the exec functions, alternate  signal
178       stacks  are  not preserved and the SA_ONSTACK flag shall be cleared for
179       all signals.
180
181       After a successful call to any of the  exec  functions,  any  functions
182       previously registered by the atexit() or pthread_atfork() functions are
183       no longer registered.
184
185       If the ST_NOSUID bit is set for the  file  system  containing  the  new
186       process  image  file,  then  the effective user ID, effective group ID,
187       saved set-user-ID, and saved set-group-ID  are  unchanged  in  the  new
188       process  image.  Otherwise,  if  the  set-user-ID  mode  bit of the new
189       process image file is set, the effective user ID  of  the  new  process
190       image  shall be set to the user ID of the new process image file. Simi‐
191       larly, if the set-group-ID mode bit of the new process  image  file  is
192       set,  the  effective  group ID of the new process image shall be set to
193       the group ID of the new process image file.  The  real  user  ID,  real
194       group  ID,  and  supplementary group IDs of the new process image shall
195       remain the same as those of the calling process  image.  The  effective
196       user  ID and effective group ID of the new process image shall be saved
197       (as the saved set-user-ID  and  the  saved  set-group-ID)  for  use  by
198       setuid().
199
200       Any  shared memory segments attached to the calling process image shall
201       not be attached to the new process image.
202
203       Any named semaphores open in the calling process shall be closed as  if
204       by appropriate calls to sem_close().
205
206       Any  blocks of typed memory that were mapped in the calling process are
207       unmapped, as if munmap() was implicitly called to unmap them.
208
209       Memory locks established by the calling process via calls to mlockall()
210       or  mlock()  shall  be removed. If locked pages in the address space of
211       the calling process are also mapped into the address  spaces  of  other
212       processes  and  are locked by those processes, the locks established by
213       the other processes shall be unaffected by the call by this process  to
214       the  exec  function.  If  the exec function fails, the effect on memory
215       locks is unspecified.
216
217       Memory mappings created in the process are unmapped before the  address
218       space is rebuilt for the new process image.
219
220       When  the  calling process image does not use the SCHED_FIFO, SCHED_RR,
221       or SCHED_SPORADIC scheduling policies, the scheduling policy and param‐
222       eters  of  the  new  process  image  and the initial thread in that new
223       process image are implementation-defined.
224
225       When the calling  process  image  uses  the  SCHED_FIFO,  SCHED_RR,  or
226       SCHED_SPORADIC  scheduling  policies, the process policy and scheduling
227       parameter settings shall not be changed by a call to an exec  function.
228       The  initial  thread in the new process image shall inherit the process
229       scheduling policy and parameters. It shall have the default system con‐
230       tention scope, but shall inherit its allocation domain from the calling
231       process image.
232
233       Per-process timers created by the  calling  process  shall  be  deleted
234       before replacing the current process image with the new process image.
235
236       All  open  message  queue  descriptors  in the calling process shall be
237       closed, as described in mq_close().
238
239       Any outstanding asynchronous I/O  operations  may  be  canceled.  Those
240       asynchronous  I/O operations that are not canceled shall complete as if
241       the exec function had not yet occurred, but any associated signal noti‐
242       fications shall be suppressed. It is unspecified whether the exec func‐
243       tion itself blocks awaiting such I/O completion. In no event,  however,
244       shall the new process image created by the exec function be affected by
245       the presence of outstanding asynchronous I/O operations at the time the
246       exec function is called. Whether any I/O is canceled, and which I/O may
247       be canceled upon exec, is implementation-defined.
248
249       The new process image shall inherit the CPU-time clock of  the  calling
250       process  image.  This inheritance means that the process CPU-time clock
251       of the process being exec-ed shall not be reinitialized or altered as a
252       result of the exec function other than to reflect the time spent by the
253       process executing the exec function itself.
254
255       The initial value of the CPU-time clock of the initial  thread  of  the
256       new process image shall be set to zero.
257
258       If  the  calling  process  is being traced, the new process image shall
259       continue to be traced into  the  same  trace  stream  as  the  original
260       process  image, but the new process image shall not inherit the mapping
261       of trace event names to trace event type identifiers that  was  defined
262       by     calls     to     the     posix_trace_eventid_open()    or    the
263       posix_trace_trid_eventid_open() functions in the calling process image.
264
265       If the calling process is a trace controller process, any trace streams
266       that  were  created  by  the  calling  process  shall  be  shut down as
267       described in the posix_trace_shutdown() function.
268
269       The thread ID of the initial thread in the new process image is unspec‐
270       ified.
271
272       The  size  and location of the stack on which the initial thread in the
273       new process image runs is unspecified.
274
275       The initial thread in the new process image shall have its cancellation
276       type  set  to PTHREAD_CANCEL_DEFERRED and its cancellation state set to
277       PTHREAD_CANCEL_ENABLED.
278
279       The initial thread in the new process image shall have all  thread-spe‐
280       cific  data  values set to NULL and all thread-specific data keys shall
281       be removed by the call to exec without running destructors.
282
283       The initial thread in the new process image shall be  joinable,  as  if
284       created with the detachstate attribute set to PTHREAD_CREATE_JOINABLE.
285
286       The  new  process  shall inherit at least the following attributes from
287       the calling process image:
288
289        *  Nice value (see nice())
290
291        *  semadj values (see semop())
292
293        *  Process ID
294
295        *  Parent process ID
296
297        *  Process group ID
298
299        *  Session membership
300
301        *  Real user ID
302
303        *  Real group ID
304
305        *  Supplementary group IDs
306
307        *  Time left until an alarm clock signal (see alarm())
308
309        *  Current working directory
310
311        *  Root directory
312
313        *  File mode creation mask (see umask())
314
315        *  File size limit (see getrlimit() and setrlimit())
316
317        *  Process signal mask (see pthread_sigmask())
318
319        *  Pending signal (see sigpending())
320
321        *  tms_utime, tms_stime, tms_cutime, and tms_cstime (see times())
322
323        *  Resource limits
324
325        *  Controlling terminal
326
327        *  Interval timers
328
329       The initial thread of the new process shall inherit at least  the  fol‐
330       lowing attributes from the calling thread:
331
332        *  Signal mask (see sigprocmask() and pthread_sigmask())
333
334        *  Pending signals (see sigpending())
335
336       All  other  process  attributes  defined in this volume of POSIX.1‐2008
337       shall be inherited in the new process image from the old process image.
338       All  other  thread  attributes  defined  in this volume of POSIX.1‐2008
339       shall be inherited in the initial thread in the new process image  from
340       the  calling  thread  in  the  old  process  image.  The inheritance of
341       process or thread attributes not defined by this volume of POSIX.1‐2008
342       is implementation-defined.
343
344       A  call  to  any exec function from a process with more than one thread
345       shall result in all threads being terminated  and  the  new  executable
346       image  being  loaded  and  executed. No destructor functions or cleanup
347       handlers shall be called.
348
349       Upon successful completion, the exec functions shall  mark  for  update
350       the  last data access timestamp of the file. If an exec function failed
351       but was able to locate the process image file, whether  the  last  data
352       access  timestamp  is marked for update is unspecified. Should the exec
353       function succeed, the process image file shall be  considered  to  have
354       been opened with open().  The corresponding close() shall be considered
355       to occur at a time after this open, but before process  termination  or
356       successful  completion  of  a  subsequent call to one of the exec func‐
357       tions, posix_spawn(), or posix_spawnp().  The argv[] and envp[]  arrays
358       of  pointers  and  the strings to which those arrays point shall not be
359       modified by a call to one of the exec functions,  except  as  a  conse‐
360       quence of replacing the process image.
361
362       The saved resource limits in the new process image are set to be a copy
363       of the process' corresponding hard and soft limits.
364

RETURN VALUE

366       If one of the exec functions returns to the calling process  image,  an
367       error  has  occurred;  the return value shall be −1, and errno shall be
368       set to indicate the error.
369

ERRORS

371       The exec functions shall fail if:
372
373       E2BIG  The number of bytes used by the  new  process  image's  argument
374              list  and  environment  list  is greater than the system-imposed
375              limit of {ARG_MAX} bytes.
376
377       EACCES The new process image file is not a regular file and the  imple‐
378              mentation does not support execution of files of its type.
379
380       EINVAL The  new process image file has appropriate privileges and has a
381              recognized executable binary format, but  the  system  does  not
382              support execution of a file with this format.
383
384       The exec functions, except for fexecve(), shall fail if:
385
386       EACCES Search  permission  is  denied for a directory listed in the new
387              process image file's path prefix, or the new process image  file
388              denies execution permission.
389
390       ELOOP  A loop exists in symbolic links encountered during resolution of
391              the path or file argument.
392
393       ENAMETOOLONG
394              The  length  of  a  component  of  a  pathname  is  longer  than
395              {NAME_MAX}.
396
397       ENOENT A  component  of  path or file does not name an existing file or
398              path or file is an empty string.
399
400       ENOTDIR
401              A component of the new process image file's path prefix names an
402              existing file that is neither a directory nor a symbolic link to
403              a directory, or the new process image file's  pathname  contains
404              at  least  one  non-<slash>  character and ends with one or more
405              trailing <slash> characters  and  the  last  pathname  component
406              names  an  existing  file that is neither a directory nor a sym‐
407              bolic link to a directory.
408
409       The exec functions, except for execlp() and execvp(), shall fail if:
410
411       ENOEXEC
412              The new process image file has the appropriate access permission
413              but has an unrecognized format.
414
415       The fexecve() function shall fail if:
416
417       EBADF  The  fd argument is not a valid file descriptor open for execut‐
418              ing.
419
420       The exec functions may fail if:
421
422       ENOMEM The new process image requires more memory than  is  allowed  by
423              the hardware or system-imposed memory management constraints.
424
425       The exec functions, except for fexecve(), may fail if:
426
427       ELOOP  More  than  {SYMLOOP_MAX} symbolic links were encountered during
428              resolution of the path or file argument.
429
430       ENAMETOOLONG
431              The length of the path argument or the length  of  the  pathname
432              constructed  from the file argument exceeds {PATH_MAX}, or path‐
433              name resolution of a  symbolic  link  produced  an  intermediate
434              result with a length that exceeds {PATH_MAX}.
435
436       ETXTBSY
437              The  new  process  image  file is a pure procedure (shared text)
438              file that is currently open for writing by some process.
439
440       The following sections are informative.
441

EXAMPLES

443   Using execl()
444       The following example executes the ls command, specifying the  pathname
445       of  the  executable  (/bin/ls) and using arguments supplied directly to
446       the command to produce single-column output.
447
448           #include <unistd.h>
449
450           int ret;
451           ...
452           ret = execl ("/bin/ls", "ls", "-1", (char *)0);
453
454   Using execle()
455       The following example is similar to Using  execl().   In  addition,  it
456       specifies the environment for the new process image using the env argu‐
457       ment.
458
459           #include <unistd.h>
460
461           int ret;
462           char *env[] = { "HOME=/usr/home", "LOGNAME=home", (char *)0 };
463           ...
464           ret = execle ("/bin/ls", "ls", "-l", (char *)0, env);
465
466   Using execlp()
467       The following example searches for the location of the ls command among
468       the directories specified by the PATH environment variable.
469
470           #include <unistd.h>
471
472           int ret;
473           ...
474           ret = execlp ("ls", "ls", "-l", (char *)0);
475
476   Using execv()
477       The  following  example  passes  arguments to the ls command in the cmd
478       array.
479
480           #include <unistd.h>
481
482           int ret;
483           char *cmd[] = { "ls", "-l", (char *)0 };
484           ...
485           ret = execv ("/bin/ls", cmd);
486
487   Using execve()
488       The following example passes arguments to the ls  command  in  the  cmd
489       array,  and  specifies  the environment for the new process image using
490       the env argument.
491
492           #include <unistd.h>
493
494           int ret;
495           char *cmd[] = { "ls", "-l", (char *)0 };
496           char *env[] = { "HOME=/usr/home", "LOGNAME=home", (char *)0 };
497           ...
498           ret = execve ("/bin/ls", cmd, env);
499
500   Using execvp()
501       The following example searches for the location of the ls command among
502       the  directories specified by the PATH environment variable, and passes
503       arguments to the ls command in the cmd array.
504
505           #include <unistd.h>
506
507           int ret;
508           char *cmd[] = { "ls", "-l", (char *)0 };
509           ...
510           ret = execvp ("ls", cmd);
511

APPLICATION USAGE

513       As the state of conversion descriptors and message catalog  descriptors
514       in  the  new process image is undefined, conforming applications should
515       not rely on their use and should close them prior to calling one of the
516       exec functions.
517
518       Applications  that  require  other than the default POSIX locale as the
519       global locale in the new process image should call setlocale() with the
520       appropriate parameters.
521
522       When assigning a new value to the environ variable, applications should
523       ensure that the environment to which it will point  contains  at  least
524       the following:
525
526        1. Any implementation-defined variables required by the implementation
527           to provide a conforming environment. See the  _CS_V7_ENV  entry  in
528           <unistd.h> and confstr() for details.
529
530        2. A  value  for  PATH which finds conforming versions of all standard
531           utilities before any other versions.
532
533       The same constraint applies to the envp array  passed  to  execle()  or
534       execve(), in order to ensure that the new process image is invoked in a
535       conforming environment.
536
537       Applications should not execute programs with  file  descriptor  0  not
538       open  for  reading or with file descriptor 1 or 2 not open for writing,
539       as this might cause the executed program to misbehave. In order not  to
540       pass  on  these  file  descriptors to an executed program, applications
541       should not just close them but should  reopen  them  on,  for  example,
542       /dev/null.   Some  implementations  may  reopen them automatically, but
543       applications should not rely on this being done.
544
545       If an application wants to perform a checksum test of  the  file  being
546       executed before executing it, the file will need to be opened with read
547       permission to perform the checksum test.
548
549       Since execute permission is checked by fexecve(), the file  description
550       fd need not have been opened with the O_EXEC flag. However, if the file
551       to be executed denies read and write permission for the process prepar‐
552       ing to do the exec, the only way to provide the fd to fexecve() will be
553       to use the O_EXEC flag when opening fd.  In this case, the  application
554       will  not  be able to perform a checksum test since it will not be able
555       to read the contents of the file.
556
557       Note that when a file descriptor is opened with  O_RDONLY,  O_RDWR,  or
558       O_WRONLY mode, the file descriptor can be used to read, read and write,
559       or write the file, respectively, even if the mode of the  file  changes
560       after  the  file  was  opened. Using the O_EXEC open mode is different;
561       fexecve() will ignore the mode that was used when the  file  descriptor
562       was  opened  and  the exec will fail if the mode of the file associated
563       with fd does not grant execute permission to the calling process at the
564       time fexecve() is called.
565

RATIONALE

567       Early  proposals  required  that  the value of argc passed to main() be
568       ``one or greater''. This was driven by the same requirement  in  drafts
569       of the ISO C standard.  In fact, historical implementations have passed
570       a value of zero when no arguments are supplied to  the  caller  of  the
571       exec  functions.  This  requirement was removed from the ISO C standard
572       and subsequently removed from this volume of POSIX.1‐2008 as well.  The
573       wording,  in particular the use of the word should, requires a Strictly
574       Conforming POSIX Application to pass at least one argument to the  exec
575       function, thus guaranteeing that argc be one or greater when invoked by
576       such an application. In fact, this is good practice, since many  exist‐
577       ing  applications reference argv[0] without first checking the value of
578       argc.
579
580       The requirement on a Strictly Conforming POSIX Application also  states
581       that  the value passed as the first argument be a filename string asso‐
582       ciated with the process being started. Although some existing  applica‐
583       tions  pass  a  pathname  rather than a filename string in some circum‐
584       stances, a filename string is more generally useful, since  the  common
585       usage of argv[0] is in printing diagnostics. In some cases the filename
586       passed is not the actual filename of the file; for example, many imple‐
587       mentations  of  the  login  utility  use  a  convention  of prefixing a
588       <hyphen> ('‐') to the actual filename, which indicates to  the  command
589       interpreter being invoked that it is a ``login shell''.
590
591       Historically,  there  have  been two ways that implementations can exec
592       shell scripts.
593
594       One common historical implementation is that the execl(), execv(), exe‐
595       cle(),  and  execve()  functions return an [ENOEXEC] error for any file
596       not recognizable as executable, including a shell script. When the exe‐
597       clp()  and  execvp()  functions  encounter such a file, they assume the
598       file to be a shell script and invoke a  known  command  interpreter  to
599       interpret  such  files.   This  is  now required by POSIX.1‐2008. These
600       implementations of execvp() and execlp() only give the [ENOEXEC]  error
601       in the rare case of a problem with the command interpreter's executable
602       file. Because of these implementations, the [ENOEXEC] error is not men‐
603       tioned  for  execlp()  or  execvp(), although implementations can still
604       give it.
605
606       Another way that some historical implementations handle  shell  scripts
607       is  by  recognizing  the  first  two bytes of the file as the character
608       string "#!" and using the remainder of the first line of  the  file  as
609       the name of the command interpreter to execute.
610
611       One  potential  source of confusion noted by the standard developers is
612       over how the contents of a process image file affect  the  behavior  of
613       the  exec  family  of  functions. The following is a description of the
614       actions taken:
615
616        1. If the process image file is a valid executable (in a  format  that
617           is executable and valid and having appropriate privileges) for this
618           system, then the system executes the file.
619
620        2. If the process image file has appropriate privileges and  is  in  a
621           format  that is executable but not valid for this system (such as a
622           recognized binary for another architecture), then this is an  error
623           and errno is set to [EINVAL] (see later RATIONALE on [EINVAL]).
624
625        3. If  the  process  image  file has appropriate privileges but is not
626           otherwise recognized:
627
628            a. If this is a call to execlp() or execvp(), then they  invoke  a
629               command  interpreter  assuming that the process image file is a
630               shell script.
631
632            b. If this is not a call to execlp() or execvp(),  then  an  error
633               occurs and errno is set to [ENOEXEC].
634
635       Applications  that do not require to access their arguments may use the
636       form:
637
638           main(void)
639
640       as specified in the ISO C standard. However,  the  implementation  will
641       always  provide  the  two arguments argc and argv, even if they are not
642       used.
643
644       Some implementations provide a third argument to  main()  called  envp.
645       This  is  defined  as  a pointer to the environment. The ISO C standard
646       specifies invoking main() with two arguments, so  implementations  must
647       support   applications   written   this   way.  Since  this  volume  of
648       POSIX.1‐2008 defines the global variable environ, which  is  also  pro‐
649       vided  by historical implementations and can be used anywhere that envp
650       could be used, there is no  functional  need  for  the  envp  argument.
651       Applications should use the getenv() function rather than accessing the
652       environment directly via either envp or environ.   Implementations  are
653       required  to  support  the two-argument calling sequence, but this does
654       not prohibit an implementation from  supporting  envp  as  an  optional
655       third argument.
656
657       This  volume  of  POSIX.1‐2008  specifies  that  signals set to SIG_IGN
658       remain set to SIG_IGN, and that the new process image inherits the sig‐
659       nal  mask of the thread that called exec in the old process image. This
660       is consistent with historical implementations, and it permits some use‐
661       ful  functionality,  such  as  the nohup command. However, it should be
662       noted that many existing applications wrongly assume  that  they  start
663       with  certain  signals  set  to the default action and/or unblocked. In
664       particular, applications written with a simpler signal model that  does
665       not include blocking of signals, such as the one in the ISO C standard,
666       may not behave properly if invoked with some  signals  blocked.  There‐
667       fore,  it  is  best not to block or ignore signals across execs without
668       explicit reason to do so, and especially not to  block  signals  across
669       execs of arbitrary (not closely cooperating) programs.
670
671       The  exec  functions always save the value of the effective user ID and
672       effective group ID of the  process  at  the  completion  of  the  exec,
673       whether  or  not the set-user-ID or the set-group-ID bit of the process
674       image file is set.
675
676       The statement about argv[] and envp[] being constants  is  included  to
677       make explicit to future writers of language bindings that these objects
678       are completely constant. Due to a limitation of the ISO C standard,  it
679       is not possible to state that idea in standard C. Specifying two levels
680       of constqualification for the argv[] and  envp[]  parameters  for  the
681       exec  functions  may  seem  to  be the natural choice, given that these
682       functions do not modify either the array of pointers or the  characters
683       to  which the function points, but this would disallow existing correct
684       code.  Instead, only the array of pointers is noted  as  constant.  The
685       table  of  assignment  compatibility for dst=src derived from the ISO C
686       standard summarizes the compatibility:
687
688┌────────────────────┬──────────┬────────────────┬───────────────┬─────────────────────┐
689dst: │ char *[] const char *[] char *const[] const char *const[] 
690├────────────────────┼──────────┼────────────────┼───────────────┼─────────────────────┤
691src:                │          │                │               │                     │
692char *[]            │  VALID   │       —        │     VALID     │          —          │
693const char *[]      │    —     │     VALID      │       —       │        VALID        │
694char * const []     │    —     │       —        │     VALID     │          —          │
695const char *const[] │    —     │       —        │       —       │        VALID        │
696└────────────────────┴──────────┴────────────────┴───────────────┴─────────────────────┘
697       Since all existing code has a source type matching the first  row,  the
698       column  that gives the most valid combinations is the third column. The
699       only other possibility is the fourth column, but using it would require
700       a cast on the argv or envp arguments. It is unfortunate that the fourth
701       column cannot be used, because the declaration a non-expert would natu‐
702       rally use would be that in the second row.
703
704       The  ISO C  standard and this volume of POSIX.1‐2008 do not conflict on
705       the use of environ, but some historical implementations of environ  may
706       cause  a  conflict. As long as environ is treated in the same way as an
707       entry point (for example, fork()), it conforms  to  both  standards.  A
708       library  can  contain  fork(),  but if there is a user-provided fork(),
709       that fork() is given precedence and no problem ensues. The situation is
710       similar  for  environ: the definition in this volume of POSIX.1‐2008 is
711       to be used if there is no user-provided environ to take precedence.  At
712       least three implementations are known to exist that solve this problem.
713
714       E2BIG  The limit {ARG_MAX} applies not just to the size of the argument
715              list, but to the sum of that and the  size  of  the  environment
716              list.
717
718       EFAULT Some  historical  systems  return [EFAULT] rather than [ENOEXEC]
719              when the new process image file is corrupted. They are  non-con‐
720              forming.
721
722       EINVAL This  error  condition  was  added  to  POSIX.1‐2008 to allow an
723              implementation to detect executable files generated for  differ‐
724              ent  architectures,  and indicate this situation to the applica‐
725              tion. Historical implementations of shells, execvp(),  and  exe‐
726              clp()  that encounter an [ENOEXEC] error will execute a shell on
727              the assumption that the file is a shell script.  This  will  not
728              produce  the  desired effect when the file is a valid executable
729              for a different architecture. An implementation may  now  choose
730              to  avoid  this  problem by returning [EINVAL] when a valid exe‐
731              cutable for a different architecture is encountered.  Some  his‐
732              torical  implementations  return  [EINVAL]  to indicate that the
733              path argument contains a character with the high order bit  set.
734              The  standard  developers chose to deviate from historical prac‐
735              tice for the following reasons:
736
737                    1. The new utilization of [EINVAL] will provide some  mea‐
738                       sure of utility to the user community.
739
740                    2. Historical  use  of  [EINVAL]  is  not acceptable in an
741                       internationalized operating environment.
742
743       ENAMETOOLONG
744              Since the file pathname may be constructed by taking elements in
745              the  PATH  variable and putting them together with the filename,
746              the [ENAMETOOLONG] error condition could also  be  reached  this
747              way.
748
749       ETXTBSY
750              System  V  returns  this  error when the executable file is cur‐
751              rently  open  for  writing  by  some  process.  This  volume  of
752              POSIX.1‐2008 neither requires nor prohibits this behavior.
753
754       Other systems (such as System V) may return [EINTR] from exec.  This is
755       not addressed by this volume of POSIX.1‐2008, but  implementations  may
756       have a window between the call to exec and the time that a signal could
757       cause one of the exec calls to return with [EINTR].
758
759       An explicit statement  regarding  the  floating-point  environment  (as
760       defined  in  the  <fenv.h>  header) was added to make it clear that the
761       floating-point environment is set to its default when a call to one  of
762       the  exec  functions succeeds. The requirements for inheritance or set‐
763       ting to the default for other process and thread start-up functions  is
764       covered  by  more  generic  statements in their descriptions and can be
765       summarized as follows:
766
767       posix_spawn() Set to default.
768
769       fork()        Inherit.
770
771       pthread_create()
772                     Inherit.
773
774       The purpose of the fexecve() function is to  enable  executing  a  file
775       which  has  been  verified  to  be the intended file. It is possible to
776       actively check the file by reading from the file descriptor and be sure
777       that  the file is not exchanged for another between the reading and the
778       execution. Alternatively, an function like openat() can be used to open
779       a file which has been found by reading the content of a directory using
780       readdir().
781

FUTURE DIRECTIONS

783       None.
784

SEE ALSO

786       alarm(), atexit(), chmod(), close(), confstr(), exit(), fcntl(),
787       fork(), fstatvfs(), getenv(), getitimer(), getrlimit(), mknod(),
788       mmap(), nice(), open(), posix_spawn(), posix_trace_create(),
789       posix_trace_event(), posix_trace_eventid_equal(), pthread_atfork(),
790       pthread_sigmask(), putenv(), readdir(), semop(), setlocale(), shmat(),
791       sigaction(), sigaltstack(), sigpending(), system(), times(), ulimit(),
792       umask()
793
794       The Base Definitions volume of  POSIX.1‐2008,  Chapter  8,  Environment
795       Variables, <unistd.h>
796
798       Portions  of  this text are reprinted and reproduced in electronic form
799       from IEEE Std 1003.1, 2013 Edition, Standard for Information Technology
800       --  Portable  Operating  System  Interface (POSIX), The Open Group Base
801       Specifications Issue 7, Copyright (C) 2013 by the Institute of Electri‐
802       cal  and  Electronics  Engineers,  Inc  and  The  Open Group.  (This is
803       POSIX.1-2008 with the 2013 Technical Corrigendum  1  applied.)  In  the
804       event of any discrepancy between this version and the original IEEE and
805       The Open Group Standard, the original IEEE and The Open Group  Standard
806       is  the  referee document. The original Standard can be obtained online
807       at http://www.unix.org/online.html .
808
809       Any typographical or formatting errors that appear  in  this  page  are
810       most likely to have been introduced during the conversion of the source
811       files to man page format. To report such errors,  see  https://www.ker
812       nel.org/doc/man-pages/reporting_bugs.html .
813
814
815
816IEEE/The Open Group                  2013                             EXEC(3P)
Impressum