C++中调用外部可执行程序的方法--创建子进程

在C++中,通过创建子进程的方法,可以在程序中像调用函数一样调用外部可执行程序。
方法如下:
  1. 使用fork()函数创建子进程;
  2. 主进程暂停,通过execlp()在子进程中调用外部可执行文件;
  3. 等待子进程完成之后,主进程继续。
    代码如下:
//主进程代码
#include
#include
#include
//创建子进程并在其中执行可执行文件,需要包含以下三个头文件///
#include
#include
#include
/////////////////////////////////////////
using namespace std;
int str2num(string s)
{
int num;
stringstream ss(s);
ss>>num;
return num;
}
class date
{
public:
    date(int y, int m, int d);
    ~date();
    void disp();
private:
    int year,month,day;
};

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

{
//   char* year = "2016";
//  char* month = "03";
//  char* day = "06";
//  char* arginput[] = [year month day];
    int status;
    pid_t ret = fork();
    if (ret<0)
        cout<<" process created failed!\n";
    else if (ret==0)
    {
        cout<<"in the child process"<" now!\n";
        ret=execlp("/home/mayaxiong/C++/a.out","3","2016","03","06",NULL);
        cout<<"execute process test sucessfully!\n";
//      else 
//cout<<"execute process test failed!\n";
    }
    else
    {
        cout<<"in the parent process"<" now!\n";
        waitpid(ret,&status,0);//

//  execlp("ls","ls","-al","/home/mayaxiong/C++/a.out",(char *)0);
    date today(str2num(argv[1]),str2num(argv[2]),str2num(argv[3]));
    //date today(argv[1],argv[2],argv[3]);
    today.disp();
    }
    return 0;
}
date::date(int y ,int m, int d)
{
year = y;
month = m;
day = d;
cout<<"construction complete!\n";
}
date::~date()
{
cout<<"deconstruction complete!\n";
}
void date::disp()
{
cout<<"year:"<"\nmonth:"<"\nday:"<"\n";
}

///////子进程代码如下  被编译为a.out的可执行文件

     #include
#include
#include

using namespace std;
int str2num(string s)
{
int num;
stringstream ss(s);
ss>>num;
return num;
}
class date
{
public:
    date(int y, int m, int d);
    ~date();
    void disp();
private:
    int year,month,day;
};

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

{
    date today(str2num(argv[1]),str2num(argv[2]),str2num(argv[3]));
    today.disp();
    cout<<"i am an external excute~\n";
    return 0;
}
date::date(int y ,int m, int d)
{
year = y;
month = m;
day = d;
cout<<"construction complete!\n";
}
date::~date()
{
cout<<"deconstruction complete!\n";
}
void date::disp()
{
cout<<"year:"<"\nmonth:"<"\nday:"<"\n";
}

执行结果如下:

C++中调用外部可执行程序的方法--创建子进程_第1张图片
那么,如何在程序中调用多个外部可执行程序呢?能够嵌套的调用吗?以后遇到这种问题的时候补充一下。

你可能感兴趣的:(c++)