execl族函数的作用
exel族函数用于调用一个已经存在的可执行程序,将该程序的运行需要的代码区和数据区的数据覆盖原进程,这样就可以实现在一个进程中调度另一个进程.
简单实现一个小功能来看一看
mytest.c
#include <stdio.h>
#include <unistd.h>
int main(){
printf("I am mytest.c , pid = %d, ppid = %d\n",getpid(),getppid());
execl("/home/lxs/c/execl/text.py","./text.py",NULL);
printf("error\n");
return 0;
}
text.py
print("I am Python!!")
执行结果(用c 语言调用了一个python程序)
exec族函数详解
一共六个函数,函数的前四个字母都为exec.
#include <unistd.h>
int execl(const char *pathname, const char *arg, ...
/* (char *) NULL */);
int execlp(const char *file, const char *arg, ...
/* (char *) NULL */);
int execle(const char *pathname, const char *arg, ...
/*, (char *) NULL, char *const envp[] */);
int execv(const char *pathname, char *const argv[]);
int execvp(const char *file, char *const argv[]);
int execvpe(const char *file, char *const argv[],
char *const envp[]);
这些函数的命名规则:
l(list) 代表以列表的形式传参
v(vector)代表以数组的形式进行传参
p(path) 代表自主搜索环境变量,不需要传路径
e(ebv) 代表自主维护环境变量
调用六个函数
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <sys/types.h>
void Child1(){
printf("I am child1, I show execl\n");
execl("/usr/bin/ls","ls","-a","-l","--color",NULL);
exit(1);
}
void Child2(){
printf("I am child2, I show execv\n");
char* const argv[] = {
"ls",
"-a",
"-l",
"--color",
NULL
};
execv("/usr/bin/ls",argv);
exit(1);
}
void Child3(){
printf("I am child3, I show execlp\n");
execlp("ls","ls","-a","-l","--color",NULL);
exit(1);
}
void Child4(){
printf("I am child4, I show execvp\n");
char* const argv[] = {
"ls",
"-a",
"-l",
"--color",
NULL
};
execvp("ls",argv);
exit(1);
}
void Child5(){
printf("I am child5, I show execle\n");
char* const envp[] = {
"HAHA = 1111111",
"HEHE = 2222222",
NULL
};
execle("/home/lxs/c/execl/test","test",NULL,envp);
exit(1);
}
void Child6(){
printf("I am child6, I show execvpe\n");
char* const argv[] = {
"test",
NULL
};
char* const envp[] = {
"HAHA = 1111111",
"HEHE = 2222222",
NULL
};
execvpe("./test",argv,envp);
exit(1);
}
int main(){
pid_t num[10];
num[1] = fork();
if(num[1] == 0){
Child1();
}
sleep(1);
num[2] = fork();
if(num[2] == 0){
Child2();
}
sleep(1);
num[3] = fork();
if(num[3] == 0){
Child3();
}
sleep(1);
num[4] = fork();
if(num[4] == 0){
Child4();
}
sleep(1);
num[5] = fork();
if(num[5] == 0){
Child5();
}
sleep(1);
num[6] = fork();
if(num[6] == 0){
Child6();
}
sleep(1);
int stat = 0;
for(int i = 1;i<=6;i++){
pid_t rid = waitpid(num[i],&stat,0);
if(rid > 0){
printf("wait child%d sucess,childexit code:%d\n",i,WEXITSTATUS(stat));
}
}
}
运行结果