現在、C++ を使用して Linux で新しいプログラムを実行するために子プロセスを開始する必要があるプロジェクトに取り組んでおり、標準入力と出力 (C++ のように、それらはcin
とcout
) をファイルにリダイレクトする必要があります。 . これは、子プロセスでは、標準入力と標準出力が両方ともファイルであることを意味します。子プロセスは、ファイル (名前は ) から入力を読み取り、ファイル (名前はinput.txt
) に出力しますoutput.txt
。
cin.rdbuf()
andを使用することで、実際に親プロセスでandをcout.rdbuf()
リダイレクトできます。ただし、子プロセスがコマンドを開始すると機能しません。子プロセスがコマンドを実行すると、標準入出力が正常に戻るようです。cin
cout
execl()
execl()
誰でもこの問題を解決できますか? 私はここ数日混乱しており、抜け道を見つけることができません。
コードは次のとおりです。
//main.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();
}
//executor.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;
};
PSは、 から読み込んで出力/home/test
する単純なプログラムです。cin
cout