一、函数原型
SYNOPSIS
#include <unistd.h>
extern char **environ;
int execl(const char *path, const char *arg, ...
/* (char *) NULL */);
int execlp(const char *file, const char *arg, ...
/* (char *) NULL */);
int execle(const char *path, const char *arg, ...
/*, (char *) NULL, char * const envp[] */);
int execv(const char *path, char *const argv[]);
int execvp(const char *file, char *const argv[]);
int execvpe(const char *file, char *const argv[],
char *const envp[]);
二、函数功能
DESCRIPTION
The exec() family of functions replaces the current process image with a new process image.
exec()函数族将当前进程映像替换为一个新的进程映像。
三、返回值
RETURN VALUE
The exec() functions return only if an error has occurred. The return value is -1, and errno is set to indicate the error.
exec()函数仅在发生错误时返回。返回值为-1,设置errno以指示错误。
四、实例
1、execl()
if(-1 == execl("/bin/ls", "ls", "-l", NULL)){
perror("execl");
exit(EXIT_FAILURE);
}
execl()、execlp()和execle()函数中的常量char*arg和后续省略号可以看作是arg0、arg1、。。。,argn。它们一起描述了指向以null结尾的字符串的一个或多个指针的列表,这些字符串表示执行程序可用的参数列表。按照惯例,第一个参数应该指向与正在执行的文件关联的文件名。参数列表必须以null指针终止,并且由于这些参数是可变函数,因此该指针必须为cast(char*)null。
2、execlp()
if(-1 == execlp("ls", "ls", "-l", NULL)){
perror("execlp");
exit(EXIT_FAILURE);
}
execlp()、execvp()和execvpe()函数复制操作如果指定的文件名称不包含斜杠(/)字符。该文件在目录中查找路径环境中指定的目录路径名的冒号分隔列表环境变量。如果未定义此变量,则路径列表默认为当前目录,后跟目录列表由confstr(_CS_路径)返回。(此confstr(3)调用通常返回值“/bin:/usr/bin”。)
环境变量更改方法:回到用户目录,vim .bashrc 后,Shift+G跳到最后一行,添加一行export PATH=$PATH:/home/tanyaduckal/buildroot/output/host/bin。(绿色处为你想要使用的进程所在的位置)
3、execle()
<execle.c>
char *envp[3] = {"Hello", "World", NULL};
if(-1 == execle("./demo", "demo", NULL, envp)){
perror("execle");
exit(EXIT_FAILURE);
}
<demo.c>
extern char **environ;
for(; NULL != *environ; environ++){
fputs(*environ, stdout);
}
putchar(10);
execle()和execvpe()函数允许调用方通过参数envp指定已执行程序的环境。envp参数是指向以null结尾的字符串的指针数组,必须由null指针终止。其他函数从调用进程中的外部变量environ获取新进程映像的环境。
4、execv()
char *arg[] = {"ps", "-aux", NULL};
if(-1 == execv("/bin/ps", arg)){
perror("execv");
exit(EXIT_FAILURE);
}
execv()、execvp()和execvpe()函数提供指向以null结尾的字符串的指针数组,这些字符串表示新程序可用的参数列表。按照惯例,第一个参数应该指向与正在执行的文件关联的文件名。指针数组必须由空指针终止。
5、execvp()
char *arg[] = {"ps", "-aux", NULL};
if(-1 == execvp("ps", arg)){
perror("execvp");
exit(EXIT_FAILURE);
}
6、execvpe()
<execvpe.c>
char *arg[] = {"demo", NULL};
char *envp[] = {"HELLO", "WORLD", NULL};
if(-1 == execvpe("demo", arg, envp)){
perror("execvpe");
exit(EXIT_FAILURE);
}
<demo.c>
extern char **environ;
for(; NULL != *environ; environ++){
fputs(*environ, stdout);
}
putchar(10);