execve函数作用是执行一个新的程序,程序可以是二进制的可执行程序,也可以是shell、pathon脚本
函数原型:
int execve(const char * filename,char * const argv[ ],char * const envp[ ]);
参数介绍:
filename:程序所在的路径
argv:传递给程序的参数,数组指针argv必须以程序(filename)开头,NULL结尾
envp:传递给程序的新环境变量,无论是shell脚本,还是可执行文件都可以使用此环境变量,必须以NULL结尾
函数返回值:
成功无返回值,失败返回-1
例子1,调用可执行程序
main.c---->main程序
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
char *envp[] = {"T1=222","T2=333",NULL};
char *argv_send[] = {"./execve_test","1","2",NULL};
execve("./execve_test",argv_send,envp);
printf("do this.....\r\n");
return 0;
}
execve_test.c---->execve_test程序
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
extern char **environ;
int main(int argc, char *argv[])
{
int i = 0;
//打印envp,新环境变量
for( i = 0; environ[i] != NULL; i++ )
{
printf("environ[%d]:%s\r\n",i,environ[i]);
}
printf("\r\n\r\n");
//打印argv,参数
for( i = 0; i < argc; i++ )
{
printf("argv[%d]:%s\r\n",i,argv[i]);
}
return 0;
}
执行程序:./main
执行结果:
environ[0]:T1=222
environ[1]:T2=333
argv[0]:./execve_test
argv[1]:1
argv[2]:2
例子2,调用shell脚本
main.c---->main程序
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
char *envp[] = {"T1=222","T2=333",NULL};
char *argv_send[] = {"./execve_shell.sh","1","2",NULL};
execve("./execve_shell.sh",argv_send,envp);
printf("do this.....\r\n");
return 0;
}
execve_shell.sh脚本
#!/bin/bash
echo $0 $1 $2
echo $T1
echo $T2
执行程序:./main
执行结果:
./execve_shell.sh 1 2
222
333