一 点睛
exec用被执行的程序(新的程序)替换调用它(调用exec)的程序。相对于fork函数会创建一个新的进程,产生一个新的PID,exec会启动一个新的程序替换当前的进程,且PID不变。
exec函数族的用法参考:https://blog.csdn.net/amoscykl/article/details/80354052
下面是函数族中execl()函数用法实战。
二 使用execl执行不带选项的命令程序pwd
1 代码
#include
int main(int argc, char* argv[])
{
// 执行/bin目录下的pwd,注意argv[0]必须要有
execl("/bin/pwd", "asdfaf", NULL);
return 0;
}
2 运行
[root@localhost test]# g++ test.cpp -o test
[root@localhost test]# ./test
/root/C++/ch05/5.5/test
3 说明
程序运行后,打印了当前路径,这和执行pwd命令一样的。虽然pwd命令不带选项,但用execl执行的时候,依然要有argv[0]这个参数。如果去掉"asdfaf",就会报错。不过这样乱写似乎不好看,一般都是写命令的名称,比如execl("/bin/pwd", "pwd", NULL);
三 使用execl执行带选项的命令程序ls
1 代码
#include
int main(void)
{
//执行/bin目录下的ls
//第一个参数为程序名ls,第二个参数为-al,第三个参数为/etc/passwd
execl("/bin/ls", "ls", "-al", "/etc/passwd", NULL);
return 0;
}
2 运行
[root@localhost test]# g++ test.cpp -o test
[root@localhost test]# ./test
-rw-r--r--. 1 root root 1110 Mar 3 16:01 /etc/passwd
3 说明
passwd是etc下的一个文件。可以在shell下直接用ls命令进行查看
[root@localhost test]# ls -la /etc/passwd
-rw-r--r--. 1 root root 1110 Mar 3 16:01 /etc/passwd
程序中,execl的第二个参数(相对于argv[0])其实没什么用处,我们即使随便输入一个字符串,效果也是一样的。
对于execl函数,只要提供程序的全路径和argv[1]开始的参数信息,就可以了。
四 使用execl执行我们自己写的程序
1 编写我们自己写的程序
#include
using namespace std;
#include
int main(int argc, char* argv[])
{
int i;
cout <<"argc=" << argc << endl; //打印下传进来的参数个数
for(i=0;i
2 编译运行我们自己写的程序
[root@localhost test]# g++ mytest.cpp -o mytest
[root@localhost test]# ./mytest
argc=1
./mytest
will print little
my program over
3 通过execl调用我们编写的程序
#include
using namespace std;
#include
int main(int argc, char* argv[])
{
execl("mytest",NULL); //不传任何参数给mytest
cout << "-----------------main is over" << endl; //如果execl执行成功,这一行不会被执行
return 0;
}
4 编译并运行该程序
[root@localhost test]# g++ test.cpp -o test
[root@localhost test]# ./test
argc=0
will print little
my program over
在调用execl时,没有传入任何参数给mytest,因此打印了0,这说明执行自己编写的程序的时候,可以不传argv[0],这一点和执行系统命令不一样。
5 execl传入两个参数调用我们编写的程序
[root@localhost test]# cat test.cpp
#include
using namespace std;
#include
int main(int argc, char* argv[])
{
execl("mytest","two params","-p",NULL);
cout << "-----------------main is over" << endl;
return 0;
}
6 编译并运行
[root@localhost test]# g++ test.cpp -o test
[root@localhost test]# ./test
argc=2
two params
-p
will print all
my program over