この質問は、次の手順を実装しようとした結果です。
パイプを使用して 2 つのプログラム間で単純な文字列を送信する方法は?
http://tldp.org/LDP/lpg/node11.html
私の質問は、Linux Pipes as Input and Outputの質問の行に沿っていますが、より具体的です。
基本的に、私は置き換えようとしています:
/directory/program < input.txt > output.txt
ハードドライブの使用を避けるために、C++ でパイプを使用します。これが私のコードです:
//LET THE PLUMBING BEGIN
int fd_p2c[2], fd_pFc[2], bytes_read;
// "p2c" = pipe_to_child, "pFc" = pipe_from_child (see above link)
pid_t childpid;
char readbuffer[80];
string program_name;// <---- includes program name + full path
string gulp_command;// <---- includes my line-by-line stdin for program execution
string receive_output = "";
pipe(fd_p2c);//create pipe-to-child
pipe(fd_pFc);//create pipe-from-child
childpid = fork();//create fork
if (childpid < 0)
{
cout << "Fork failed" << endl;
exit(-1);
}
else if (childpid == 0)
{
dup2(0,fd_p2c[0]);//close stdout & make read end of p2c into stdout
close(fd_p2c[0]);//close read end of p2c
close(fd_p2c[1]);//close write end of p2c
dup2(1,fd_pFc[1]);//close stdin & make read end of pFc into stdin
close(fd_pFc[1]);//close write end of pFc
close(fd_pFc[0]);//close read end of pFc
//Execute the required program
execl(program_name.c_str(),program_name.c_str(),(char *) 0);
exit(0);
}
else
{
close(fd_p2c[0]);//close read end of p2c
close(fd_pFc[1]);//close write end of pFc
//"Loop" - send all data to child on write end of p2c
write(fd_p2c[1], gulp_command.c_str(), (strlen(gulp_command.c_str())));
close(fd_p2c[1]);//close write end of p2c
//Loop - receive all data to child on read end of pFc
while (1)
{
bytes_read = read(fd_pFc[0], readbuffer, sizeof(readbuffer));
if (bytes_read <= 0)//if nothing read from buffer...
break;//...break loop
receive_output += readbuffer;//append data to string
}
close(fd_pFc[0]);//close read end of pFc
}
上記の文字列が正しく初期化されていることは間違いありません。ただし、私には意味をなさない2つのことが起こります。
(1) 私が実行しているプログラムは、「入力ファイルが空です」と報告します。「<」でプログラムを呼び出していないため、入力ファイルを期待するべきではありません。代わりに、キーボード入力を期待する必要があります。さらに、「gulp_command」に含まれるテキストを読み取っているはずです。
(2) プログラムのレポート (標準出力を介して提供される) がターミナルに表示されます。このパイプの目的は stdout を文字列 "receive_output" に転送することであるため、これは奇妙です。しかし、画面に表示されているため、情報がパイプを介して変数に正しく渡されていないことがわかります。if文の最後に以下を実装すると、
cout << receive_output << endl;
文字列が空であるかのように、何も得られません。あなたが私に与えることができるどんな助けにも感謝します!
編集:明確化
私のプログラムは現在、テキスト ファイルを使用して別のプログラムと通信しています。私のプログラムは、外部プログラムによって読み取られるテキスト ファイル (例: input.txt) を書き込みます。次に、そのプログラムが output.txt を生成し、それが私のプログラムによって読み取られます。したがって、次のようなものです。
my code -> input.txt -> program -> output.txt -> my code
したがって、私のコードは現在、
system("program < input.txt > output.txt");
このプロセスをパイプを使用して置き換えたい。入力を標準入力としてプログラムに渡し、コードでそのプログラムからの標準出力を文字列に読み取らせたいと考えています。