Linux函数exec函数族:
这来函数是用来执行一些可执行文件的,常用在fork出子进程后,在子进程中执行。也就是替换子进程的东西,子进程的东西全部被替换,但只是替换,不会产生一个新的进程,进程的ID号也不会改变。
#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[]);
l代表的是list:命令行参数列表
p代表的是path:搜索file时的使用的path变量
v代表的是vector:使用命令行参数数组
e代表的是environment:使用环境变量数组
常用的函数有两个execl和execlp
参数会通过参数列表传递给执行的文件,并且以NULL结尾代表参数结束,下边通过测试代码对函数传递参数方式进行解析
以下是需要execl函数执行的文件代码,将传入的函数全部打印出来
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char*argv[])
{
for (int i =0; i < argc; i++) {
printf("argv[%d] = %s\n", i, argv[i]);
}
return 0;
}
#include <stdio.h>
#include <unistd.h>
int main(void)
{
execl("./test", "a", "b", "c", NULL);
perror("execl failed\n");
return 0;
}
函数的执行结果为
argv[0] = a
argv[1] = b
argv[2] = c
看见execl函数的第二个参数会当做test的第一个参数传入,以此类推。execl执行后函数只有在调用函数出错的情况下才返回,一旦调用成功,函数则会跳转到指定的函数中去执行,任何情况下都不会在返回。