exec家族实现的功能就是将当前正在运行的进程替换成其他程序代码运行。也就是说如果你的进程调用了exec函数族,那么当前正在运行的代码程序将全部被exec函数引进来的新程序代码所代替。
exec函数族拥有以下函数:
int execvp(const char *file, char *const argv[]);
int execvpe(const char *file, char *const argv[], char *const envp[]);
每一个exec函数都可以实现用新的进程替换当前正在运行的进程。下面来进行exec函数族详细的分析以及每一个函数的用法,在加上一个小小的示例,这样更容易懂得exec函数。
1、int execl(const char *pathname, const char *arg, ... /* (char *) NULL */);
const char *pathname : 换掉当前进程,要执行新的程序的绝对路径
const char *arg//:是一个可变参数,参数2后面可以在加上参数3,参数4,参数5...,都是指针类型,命令行参数:执行一个程序时,程序名以及程序对应参数如:ls -l -a 参数2:就是要执行的程序 参数3,4,5,6:就是执行程序 参数 选项等。
返回值:只有失败才会有返回值:-1
#include <unistd.h>
#include <iostream>
using namespace std;
// 执行/bin目录下的ls, 第一参数为程序名ls, 第二个参数为"-al", 第三个参数为"/etc/passwd"
int main()
{
if(execl("/bin/ls", "ls", "-al", "/etc/passwd", (char *) 0) < 0)
{
cout<<"execl error"<<endl;
}
else
{
cout<<"success"<<endl;
}
return 0;
}
2、int execlp(const char *file, const char *arg, ... /* (char *) NULL */);
execlp()函数:从PATH环境变量中查找文件并执行,就是把路径已经选择好是一个固定路径,相对于execl函数,可以不写上完整路径,从指定路径中查找替换的程序。
/* 执行ls -al /etc/passwd execlp()会依PATH 变量中的/bin 找到/bin/ls */
#include <unistd.h>
main()
{
execlp("ls", "ls","-al", "/etc/passwd", (char *)0);
}
3、 int execle(const char *pathname, const char *arg, .../*, (char *) NULL, char *const envp[] */);
将环境变量传递给需要替换的进程
execle.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
char * const envp[] = {"AA=11", "BB=22", NULL};
printf("Entering main ...\n");
int ret;
ret =execle("./hello", "hello", NULL, envp);
if(ret == -1)
perror("execl error");
printf("Exiting main ...\n");
return 0;
}
hello.c
#include <unistd.h>
#include <stdio.h>
extern char** environ;
int main(void)
{
printf("hello pid=%d\n", getpid());
int i;
for (i=0; environ[i]!=NULL; ++i)
{
printf("%s\n", environ[i]);
}
return 0;
}
execle.c运用了hello.c的内容
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(void)
{
printf("entering main process---\n");
int ret;
char *argv[] = {"ls","-l",NULL};
ret = execvp("ls",argv);
if(ret == -1)
perror("execl error");
printf("exiting main process ----\n");
return 0;
}
剩下的两个函数于execl的用法差不多,所以就不多说,理解就好。
int execvp(const char *file, char *const argv[]);
int execvpe(const char *file, char *const argv[], char *const envp[]);
对exec函数族的理解就是用一个新的程序替换掉当前程序,一般这种都是配合父子进程或者其他函数通信来使用。
每天记录学习日志