现在,我正在开发一个项目,其中我需要启动一个子进程来使用 C++ 在 Linux 中执行一个新程序,并且我需要重定向标准输入和输出(就像在 C++ 中一样,它们是cin
and cout
) 到一个文件。这意味着在子进程中,标准输入和输出都是文件。子进程将从文件中读取输入(其名称为input.txt
),并输出到一个文件(其名称为output.txt
).
通过使用cin.rdbuf()
and cout.rdbuf()
,我实际上可以重定向cin
and cout
在父进程中。但是当子进程启动时它不起作用execl()
命令。看来子进程执行后execl()
命令后,标准输入输出恢复正常。
任何人都可以帮助我解决这个问题吗?这几天我一直很迷茫,找不到出路。
代码如下:
//主.cpp
#include<sys/types.h>
#include<sys/time.h>
#include<sys/wait.h>
#include<sys/ptrace.h>
#include<sys/syscall.h>
#include<string>
#include"executor.cpp"
int main(int argc, char*argv[])
{
executor ex;
ex.set_path("/home/test");
ex.run_program();
}
//执行器.cpp
#include<sys/types.h>
#include<sys/time.h>
#include<sys/wait.h>
#include<sys/ptrace.h>
#include<sys/syscall.h>
#include<string.h>
#include<unistd.h>
#include<iostream>
#include<fstream>
using namespace std;
class executor{
public:
void run_program()
{
char p[50];
strcpy(p,path.c_str());
cpid = fork();
if(cpid == 0)
{
ifstream file("/home/openjudge/data.txt");
if(!file) cout<<"file open failed\n";
streambuf* x = cin.rdbuf(file.rdbuf());
ptrace(PTRACE_TRACEME,0,NULL,NULL);
execl(p,"test","NULL);
cin.rdbuf(x);
cout<<"execute failed!\n";
}
else if(cpid > 0)
{
wait(NULL);
cout<<"i'm a father\n";
}
}
void set_path(string p)
{
path = p;
}
private:
int cpid;
string path;
};
P.S. /home/test
是一个简单的程序,它读取cin
并输出到cout
;