功能:
在调用进程内部执行一个可执行文件。可执行文件既可以是二进制文件,也可以是任何Linux下可执行的脚本文件。
函数族:
exec函数族分别是:exect,execlp,execle,execv,execvp,execvpe。
函数原型:
#include <unistd.h>
extern char **environ;
int execl(const char *path,const char *arg,...);//常用
int execlp(const char *file,const char *arg,...);//带p能通过环境变量PATH查找到可执行文件,常用
int execle(const char *path,const char *arg,...,char *const envp[]);
int execv(const char *path,char *const argv[]);//常用
int execp(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环境变量,在它所指定的各目录中搜寻可执行文件。
//echoarg.c
#include <stdio.h>
int main(int argc,char **argv)
{
int i = 0;
for(i = 0;i < argc;i++){
printf("argv[%d]:%s\n",i,argv[i]);
}
return 0;
}
//execl.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main()
{
printf("before execl\n");
if(execl("./echoarg","echoarg","abc",NULL) == -1)
{
printf("execl failed\n");
}
printf("after execl\n");
return 0;
}
注:execl的第一个参数是路径名
//execlp.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main()
{
printf("before execlp\n");
if(execlp("ls","-l",NULL) == -1)
{
printf("execl failed\n");
}
printf("after execl\n");
return 0;
}
显示环境变量:
增加环境变量:
export PATH = $PATH:路径