一 点睛
execlp函数会从PATH环境变量所指得目录中查找符合参数file的文件名,找到后便执行该文件,然后将第二个以后的参数当作该文件的argv[0]、argv[1]......,最后一个参数必须用空指针(NULL)结束。
execlp函数声明如下:
int execlp(const char *filename, const char *arg, ...)
如果执行成功,则函数不会返回,执行失败则直接返回-1,失败原因存于errno中。
二 使用execlp执行不带选项的命令程序pwd
1 代码
#include <unistd.h>
int main(int argc, char* argv[])
{
execlp("pwd", "", NULL);
return 0;
}
2 编译并运行
[root@localhost test]# g++ test.cpp -o test
[root@localhost test]# ./test
/root/C++/ch05/5.8/test
3 说明
execlp的第一个函数直接用pwd这个命令程序即可,而不需要写出其全路径,因为环境变量PATH中已经包含路径/usr/bin了。
对应第二个参数为什么是空字符串,这个其实不重要,传任意字符串都可以,但必须要有,不能为NULL,否则运行会报错。这只是针对创建系统命令程序的情况,我们自己的程序无须这样。
三 使用execlp执行我们自己编写的程序
1 编写我们自己写的程序
#include <string.h>
using namespace std;
#include <iostream>
int main(int argc, char* argv[])
{
int i;
cout <<"argc=" << argc << endl; //打印下传进来的参数个数
for(i=0;i<argc;i++) //打印各个参数
cout<<argv[i]<<endl;
}
2 编译并运行
[root@localhost test]# g++ mytest.cpp -o mytest
[root@localhost test]# ./mytest hello world
argc=3
./mytest
hello
world
3 execlp调用我们编写的程序
#include <unistd.h>
using namespace std;
#include <iostream>
int main(int argc, char* argv[])
{
execl("mytest","hello","boys", NULL); //传入两个参数
cout << "------------------\n";//如果execl执行成功,这一句不会执行到的。
return 0;
}
4 运行结果
[root@localhost test]# g++ test.cpp -o test
[root@localhost test]# ./test
argc=2
hello
boys