Linux 的 exec 函数之间的区别

Linux 的 exec 函数族中函数的原型如下:

1int execl(const char *pathname, const char *arg, ...);
2int execlp(const char *file, const char *arg, ...);
3int execle(const char *pathname, const char *arg, ...);
4
5int execv(const char *pathname, char *const argv[]);
6int execvp(const char *file, char *const argv[]);
7int execve(const char *file, char *const argv[], char *const envp[]);
8
9int execvpe(const char *file, char *const argv[], char *const envp[]);  // GNU 扩展

他们的明明遵循以下规则:

  • l(list)表示通过可变参数列表传递额外参数,要额外传递一个 NULL 参数表示结尾
  • v(vector)表示通过数组传递额外参数,数组中要要额外包含一个 NULL 表示结尾
  • p(path)表示搜索 PATH 环境变量;没有 p 则不搜索,必须指定路径(绝对路径或相对路径)
  • e(environment)表示指定环境变量;没有 e 则继承当前进程的环境变量

其中 execle 比较特别,从它的命名中可以看出,它通过可变参数列表传递额外参数,并且可以指定环境变量。

但是从函数原型中看不出环境变量的参数应该怎样传递。

实际上环境变量的参数需要以数组的形式传递,并以 NULL 结尾。

示例

1// `l` 通过可变参数列表传递额外参数
2execl("/usr/bin/ls", "/home", NULL);
3
4// `p` 表示搜索 `PATH` 环境变量
5execlp("ls", "/home", NULL);
6
7// `v` 表示通过数组传递额外参数
8execv("/usr/bin/ls", {"/home", NULL});
9
10// e 表示指定环境变量,以 NULL 结尾
11execvpe("ls", {"/home", NULL}, {"PATH=/usr/bin", NULL});
1const char* envp[] = {
2    "PATH=/usr/bin",
3    NULL    // 以 NULL 结尾
4};
5
6execle("/usr/bin/ls", "/home", NULL, envp);

参考文档

1exec(3)                    Library Functions Manual                    exec(3)
2
3NAME
4       execl, execlp, execle, execv, execvp, execvpe - execute a file
5
6LIBRARY
7       Standard C library (libc, -lc)
8
9SYNOPSIS
10       #include <unistd.h>
11
12       extern char **environ;
13
14       int execl(const char *pathname, const char *arg, ...
15                       /*, (char *) NULL */);
16       int execlp(const char *file, const char *arg, ...
17                       /*, (char *) NULL */);
18       int execle(const char *pathname, const char *arg, ...
19                       /*, (char *) NULL, char *const envp[] */);
20       int execv(const char *pathname, char *const argv[]);
21       int execvp(const char *file, char *const argv[]);
22       int execvpe(const char *file, char *const argv[], char *const envp[]);
23
24   Feature Test Macro Requirements for glibc (see feature_test_macros(7)):
25
26       execvpe():
27           _GNU_SOURCE
28
29DESCRIPTION
30       The  exec() family of functions replaces the current process image with
31       a new process image.  The functions described in this manual  page  are
32       layered  on  top  of execve(2).  (See the manual page for execve(2) for
33       further details about the replacement of the current process image.)
34
35       The initial argument for these functions is the name of a file that  is
36       to be executed.
37
38       The  functions can be grouped based on the letters following the "exec"
39       prefix.
40
41   l - execl(), execlp(), execle()
42       The const char *arg and subsequent ellipses can be thought of as  arg0,
43       arg1, ..., argn.  Together they describe a list of one or more pointers
44       to  null-terminated  strings that represent the argument list available
45       to the executed program.  The first  argument,  by  convention,  should
46       point  to  the  filename  associated with the file being executed.  The
47       list of arguments must be terminated by  a  null  pointer,  and,  since
48       these are variadic functions, this pointer must be cast (char *) NULL.
49
50       By  contrast  with the 'l' functions, the 'v' functions (below) specify
51       the command-line arguments of the executed program as a vector.
52
53   v - execv(), execvp(), execvpe()
54       The char *const argv[] argument is an array of pointers to  null-termi‐
55       nated  strings  that  represent  the argument list available to the new
56       program.  The first argument, by convention, should point to the  file‐
57       name  associated  with  the file being executed.  The array of pointers
58       must be terminated by a null pointer.
59
60   e - execle(), execvpe()
61       The environment of the new process image is specified via the  argument
62       envp.   The  envp  argument  is an array of pointers to null-terminated
63       strings and must be terminated by a null pointer.
64
65       All other exec() functions (which do not include  'e'  in  the  suffix)
66       take  the environment for the new process image from the external vari‐
67       able environ in the calling process.
68
69   p - execlp(), execvp(), execvpe()
70       These functions duplicate the actions of the shell in searching for  an
71       executable  file if the specified filename does not contain a slash (/)
72       character.  The file is sought in the colon-separated list of directory
73       pathnames specified in the PATH environment variable.  If this variable
74       isn't defined, the path list defaults to a list that includes  the  di‐
75       rectories  returned  by  confstr(_CS_PATH) (which typically returns the
76       value "/bin:/usr/bin") and possibly also the current working directory;
77       see NOTES for further details.
78
79       execvpe() searches for the program using the value  of  PATH  from  the
80       caller's environment, not from the envp argument.
81
82       If  the specified filename includes a slash character, then PATH is ig‐
83       nored, and the file at the specified pathname is executed.
84
85       In addition, certain errors are treated specially.
86
87       If permission is denied for a file (the attempted execve(2) failed with
88       the error EACCES), these functions will continue searching the rest  of
89       the  search path.  If no other file is found, however, they will return
90       with errno set to EACCES.
91
92       If the header of a  file  isn't  recognized  (the  attempted  execve(2)
93       failed  with the error ENOEXEC), these functions will execute the shell
94       (/bin/sh) with the path of the file as its first  argument.   (If  this
95       attempt fails, no further searching is done.)
96
97       All  other  exec()  functions  (which do not include 'p' in the suffix)
98       take as their first argument a (relative  or  absolute)  pathname  that
99       identifies the program to be executed.
100
101RETURN VALUE
102       The  exec() functions return only if an error has occurred.  The return
103       value is -1, and errno is set to indicate the error.
104
105ERRORS
106       All of these functions may fail and set errno for  any  of  the  errors
107       specified for execve(2).
108
109ATTRIBUTES
110       For  an  explanation  of  the  terms  used in this section, see attrib‐
111       utes(7).
112       ┌───────────────────────────────────────┬───────────────┬─────────────┐
113       │ Interface                             │ Attribute     │ Value       │
114       ├───────────────────────────────────────┼───────────────┼─────────────┤
115       │ execl(), execle(), execv()            │ Thread safety │ MT-Safe     │
116       ├───────────────────────────────────────┼───────────────┼─────────────┤
117       │ execlp(), execvp(), execvpe()         │ Thread safety │ MT-Safe env │
118       └───────────────────────────────────────┴───────────────┴─────────────┘
119
120VERSIONS
121       The default search path (used when the environment does not contain the
122       variable PATH) shows some variation across systems.  It  generally  in‐
123       cludes  /bin and /usr/bin (in that order) and may also include the cur‐
124       rent working directory.  On some other systems, the current working  is
125       included after /bin and /usr/bin, as an anti-Trojan-horse measure.  The
126       glibc  implementation  long  followed the traditional default where the
127       current working directory is included at the start of the search  path.
128       However,  some  code  refactoring  during the development of glibc 2.24
129       caused the current working directory to be dropped altogether from  the
130       default  search  path.   This  accidental behavior change is considered
131       mildly beneficial, and won't be reverted.
132
133       The behavior of execlp() and execvp() when errors occur while  attempt‐
134       ing to execute the file is historic practice, but has not traditionally
135       been  documented  and is not specified by the POSIX standard.  BSD (and
136       possibly other systems) do an automatic sleep and retry if  ETXTBSY  is
137       encountered.  Linux treats it as a hard error and returns immediately.
138
139       Traditionally,  the  functions execlp() and execvp() ignored all errors
140       except for the ones described above and ENOMEM and  E2BIG,  upon  which
141       they  returned.   They  now return if any error other than the ones de‐
142       scribed above occurs.
143
144STANDARDS
145       environ
146       execl()
147       execlp()
148       execle()
149       execv()
150       execvp()
151              POSIX.1-2008.
152
153       execvpe()
154              GNU.
155
156HISTORY
157       environ
158       execl()
159       execlp()
160       execle()
161       execv()
162       execvp()
163              POSIX.1-2001.
164
165       execvpe()
166              glibc 2.11.
167
168BUGS
169       Before glibc 2.24, execl() and execle() employed realloc(3)  internally
170       and  were  consequently  not async-signal-safe, in violation of the re‐
171       quirements of POSIX.1.  This was fixed in glibc 2.24.
172
173   Architecture-specific details
174       On sparc and sparc64, execv() is provided as a system call by the  ker‐
175       nel  (with  the  prototype  shown  above) for compatibility with SunOS.
176       This function is not employed by the execv() wrapper function on  those
177       architectures.
178
179SEE ALSO
180       sh(1),  execve(2),  execveat(2),  fork(2),  ptrace(2), fexecve(3), sys‐
181       tem(3), environ(7)
182
183Linux man-pages 6.7               2023-10-31                           exec(3)