在C++中,通过创建子进程的方法,可以在程序中像调用函数一样调用外部可执行程序。
方法如下:
//主进程代码
#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";
}
执行结果如下: