3

現在、C++ を使用して Linux で新しいプログラムを実行するために子プロセスを開始する必要があるプロジェクトに取り組んでおり、標準入力と出力 (C++ のように、それらはcincout) をファイルにリダイレクトする必要があります。 . これは、子プロセスでは、標準入力と標準出力が両方ともファイルであることを意味します。子プロセスは、ファイル (名前は ) から入力を読み取り、ファイル (名前はinput.txt) に出力しますoutput.txt

cin.rdbuf()andを使用することで、実際に親プロセスでandをcout.rdbuf()リダイレクトできます。ただし、子プロセスがコマンドを開始すると機能しません。子プロセスがコマンドを実行すると、標準入出力が正常に戻るようです。cincoutexecl()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する単純なプログラムです。cincout

4

1 に答える 1

1

子の後にファイル記述子0(標準入力) と1(標準出力)をリダイレクトする必要があります。fork()

switch (fork()) {
case 0: {
    close(0);
    if (open(name, O_RDONLY) < 0) {
        deal_with_error();
    }
    ...

親プロセスで指定されたファイルを開きたい場合があります。ファイルをすぐに開いておくと、おそらくエラー処理が容易になります。この場合dup2()、正しいファイル記述子をファイルに関連付けるために使用します。

于 2012-12-06T07:24:44.617 に答える