1.君の名は

execve() – 叫做执行程序函数

就像Python中的os.system(cmd)这个函数,我们可以用这个函数来执行我们的shell脚本,单独的shell命令,或者是调用其他的程序,我们的execve()这个函数就和Python中的os.system函数类似,可以调用其他程序的执行,执行shell命令,,调用脚本等等功能。


2.定义

我们在使用这个函数的时候我们需要在程序中加入头文件

#include <unistd.h>

函数的原型:


int execve(const char *filename, char *const argv[], char *const envp[]); 

3.描述

int execve(const char *filename, char *const argv[], 
           char *const envp[]); 

execve()执行程序由 filename决定。
filename必须是一个二进制的可执行文件,或者是一个脚本以#!格式开头的解释器参数参数。如果是后者,这个解释器必须是一个可执行的有效的路径名,但是不是脚本本身,它将调用解释器作为文件名。


argv是要调用的程序执行的参数序列,也就是我们要调用的程序需要传入的参数。

envp 同样也是参数序列,一般来说他是一种键值对的形式 key=value. 作为我们是新程序的环境。

注意,argv 和envp都必须以null指针结束。 这个参数向量和我们的环境变量都能够被我们的main函数调用,比如说我们可以定义为下面这个形式:

 int main(int argc, char *argv[], char *envp[])

我们来实战一下这个函数要怎么使用。


4.调用

4.1执行shell命令


/*************************************************************************
    > File Name: caller.c
    > Author: Chicho
    > Created Time: 2016年12月06日 星期二 11:31:12
 ************************************************************************/

#include<stdio.h>
#include<unistd.h>

int main(int arg, char **args)
{
    char *argv[]={"ls","-al","/home/chicho/result/", NULL};

    char *envp[]={0,NULL}; //传递给执行文件新的环境变量数组

    execve("/bin/ls",argv,envp);

}

这个程序的功能就是使用ls 查看我们/home/chicho/result下面的文件夹的内容。
我们编译运行以下
得到的结果如下:

这个程序的功能相当于在/home/chicho/result下使用:

ls -al

4.2 调用其他程序

调用Python程序

首先程序要有可执行权限,我们需要用chmod修改一下。

比如说我们的Python程序叫做test.py

#!/usr/bin/env python
# coding=utf-8

print "hello, world!\n"

这个时候我们用我们的C程序调用我们的python程序。执行。


#include<stdio.h>
#include<unistd.h>

int main(int arg, char **args)
{
    char *argv[]={"python","/home/chicho/test/python/test.py",NULL};
    char *envp[]={0,NULL};

    execve("/usr/bin/env",argv,envp);
}

4.3 调用二进制可执行程序

/*

*  execve.c

*/

#include<unistd.h>
int main()
{
   char * argv[ ]={"./test","test_sample",(char *)0};
   char * envp[ ]={0};
   execve("./test",argv,envp);

   return 0;
}
/*

* test.c

*/

#include <stdio.h>
int main(int narg,char **args)
{

   if(narg != 2)

   {

       printf("error,the input parameter must be one!\n");
       return -1;
   }
   char *str = args[1];
   printf("the input parameter is %s\n",str);
   return 0;
}

cc -g -o test test.c

生成test应用程序

然后

cc -g -o execve execve.c

生成execve应用程序

执行./execve即可调用test应用,输出

test_sample


Reference

http://www.tutorialspoint/unix_system_calls/execve.htm















更多推荐

C语言 execve()函数使用方法