exec族函数函数的作用:
我们用fork函数创建新进程后,经常会在新进程中调用exec函数去执行另外一个程序。当进程调用exec函数时,该进程被完全替换为新程序。因为调用exec函数并不创建新进程,所以前后进程的pid并没有改变。
功能:
在调用进程内部执行一个可执行文件。可执行文件既可以是二进制文件,也可以是任何Linux下可执行的脚本文件。
函数族:
exec函数族分别是:execl, execlp, execle, execv, execvp, execvpe
返回值:
exec函数族的函数执行成功后不会返回,调用失败时,会设置errno并返回-1,然后从原程序的调用点接着往下执行。
例子说明:
1.execl()函数
#include<stdio.h>
#include<string.h>
#include<sys/types.h>
#include<unistd.h>
#include<stdlib.h>
#include <sys/wait.h>
int main()
{
printf("before execl\n");
if(execl("/bin/ls","ls","-l",NULL)== -1)
//调用 bin路径下的ls 生成的可执行文件 就是ls的功能后面加名字 后面再加-l就是增加功能
{
printf("execl failed\n");
perror("why");
}
printf("after execl\n");
return 0;
}
实现ls -l功能 因为加上路径
2.execlp()函数 无视路径
#include<stdio.h>
#include<string.h>
#include<sys/types.h>
#include<unistd.h>
#include<stdlib.h>
#include <sys/wait.h>
int main()
{
printf("before execl\n");
if(execlp("ls","ls","-l",NULL)== -1)
{
printf("execl failed\n");
perror("why");
}
printf("after execl\n");
return 0;
}
3.execv()函数 实现ls -l功能
#include<stdio.h>
#include<string.h>
#include<sys/types.h>
#include<unistd.h>
#include<stdlib.h>
#include <sys/wait.h>
int main()
{
printf("before execl\n");
char *argv[] = {"ls","-l",NULL,NULL};
if(execv("/bin/ls",argv)==-1) //相当于ls,ls,NULL,NULL
{
printf("execl failed\n");
perror("why");
}
printf("after execl\n");
return 0;
}
4.execvp()函数 无视路径
#include<stdio.h>
#include<string.h>
#include<sys/types.h>
#include<unistd.h>
#include<stdlib.h>
#include <sys/wait.h>
int main()
{
printf("before execl\n");
char *argv[] = {"ls",NULL,NULL};
if(execvp("ls",argv)==-1) //相当于ls,ls,NULL,NULL
{
printf("execl failed\n");
perror("why");
}
printf("after execl\n");
return 0;
}