简单的使用exec函数

来源:互联网 发布:条形码扫描软件 编辑:程序博客网 时间:2024/04/28 20:36

先来看一个在终端上面执行的命令(OSX):



既然知道这是一条指令,那我们来写一个代码,调用这个指令(system包含在头文件stdlib.h中)

#include "stdio.h"#include "stdlib.h"int main(){system("pause");system("ls");system("say 'End of line'");return 0;}

调用效果:



可以看出来,虽然第一行的代码system("pause");这里并没有指令pause(windows上面有)。但是程序还是可以继续执行下去,碰到了ls指令,显然得到了效果,后面的'End of line'也朗读了出来。



system函数用起来方便,但很多时候需要更规范的方法。可能需要命令行参数、甚至是环境变量调用指定程序。



同样的,我们看一看同类的exec函数族:

#include "stdio.h"#include "unistd.h"#include "errno.h"#include "string.h"int main(){if(execl("/sbin/ifconfig", "/sbin/ifconfig", NULL) == -1){if(execlp("ipconfig", "ipconfig", NULL) == -1){fprintf(stderr, "Cannot run ipconfig : %s", strerror(errno));}}return 0;}


execl可以执行在参数列表中的程序,比如上面的"/sbin/ifconfig"

 

对于exec()函数,是这么记忆的:

execle=exec+l+e=exec+参数列表+环境变量

execlp=exec+l+e=exec+参数列表+系统PATH查找

execvp= exec+v+p= exec+参数向量(就一个变量)+ 系统PATH查找

execv的调用:execl("/sbin/ifconfig", my_args);

execvp的调用:execl("/sbin/ifconfig", my_args);表明系统PATH不需要直接指明


0 0
原创粉丝点击