C++使用execl创建进程实战

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chengqiuming/article/details/88925954

一 点睛

exec用被执行的程序(新的程序)替换调用它(调用exec)的程序。相对于fork函数会创建一个新的进程,产生一个新的PID,exec会启动一个新的程序替换当前的进程,且PID不变。

exec函数族的用法参考:https://blog.csdn.net/amoscykl/article/details/80354052

下面是函数族中execl()函数用法实战。

二 使用execl执行不带选项的命令程序pwd

1 代码

#include <unistd.h>  

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 <unistd.h>  
      
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 <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;
     
    if (argc == 2&&strcmp(argv[1], "-p")==0)  //判断是否如果带了参数-p
        cout << "will print all" << endl;
    else
        cout << "will print little" << endl;
    
    cout << "my program over" << endl;
    return 0;
}

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<unistd.h>
using namespace std;
#include <iostream>
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<unistd.h>
using namespace std;
#include <iostream>
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

猜你喜欢

转载自blog.csdn.net/chengqiuming/article/details/88925954
今日推荐