exec定义以及用法
可查询:Linux函数查询
exec族函数函数的作用
当程序运行到某一位置时,调用exec族函数,该程序就会跳到exec所引用的程序中,若调用成功则不返回原来的程序,失败则返回-1,继续往下执行源程序。
注:调用exec函数并不会创建新进程
功能
在调用进程内部执行一个可执行文件。可执行文件既可以是二进制文件,也可以是任何Linux下可执行的脚本文件。
函数族
exec函数族分别是:execl, execlp, execle, execv, execvp, execvpe
#include <unistd.h>
int execl(const char *path, const char *arg, ...);
int execlp(const char *file, const char *arg, ...);
int execle(const char *path, const char *arg,..., 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[]);
返回值:
exec函数族的函数执行成功后不会返回,调用失败时,会设置errno并返回-1,然后从原程序的调用点接着往下执行。
参数说明:
path:可执行文件的路径名字
arg:可执行程序所带的参数,第一个参数为可执行文件名字,没有带路径且arg必须以NULL结束
file:如果参数file中包含/,则就将其视为路径名,否则就按 PATH环境变量,在它所指定的各目录中搜寻可执行文件。
相关用法
//可执行程序/zgh/echoParram
#include <stdio.h>
int main(int argc,char** argv)
{
int i;
for(i = 0;i < argc;i++){
printf("%s\n",argv[i]);
}
return 0;
}
#include <stdio.h>
#include <unistd.h>
int main()
{
char *argv[] = {"echoParram","abc",NULL};
printf("before exec\n");
//根据路径去寻找可执行文件
/*if(execl("/zgh/echoParram","echoParram","abc",NULL) == -1){
printf("execl failed\n");
}*/
/*if(execv("/zgh/echoParram",argvL) == -1){
printf("execv failed\n");
}*/
//根据环境变量去寻找可执行文件
/*if(execlp("echoParram","echoParram","abc",NULL) == -1){
printf("execlp failed\n");
}*/
/*if(execvp("echoParram",argvL) == -1){
printf("execvp failed\n");
}*/
printf("after exec\n");
return 0;
}