popen を使用して C++ プログラム内から perl スクリプトを実行する際に問題が発生しています。
fgets を呼び出すとすぐに、feof は 1 を返します。
これまでのところ、次のコードがあります。
std::string PerlOutput = "";
std::stringstream CommandToRun;
CommandToRun << "perl " << ScriptFile << " " << ParametersToPass; //Both variables are type std::string
std::cout << "Executing perl script, command to execute is:\n" + CommandToRun.str() << "\n";
FILE * perl_outpipe = popen(CommandToRun.str().c_str(), "r");
unsigned int MaxLineLen = 512;
char buffer[MaxLineLen];
while(!feof(perl_outpipe))
{
if(fgets(buffer, MaxLineLen, perl_outpipe) != NULL)
{
PerlOutput.append(buffer);
}
}
pclose(perl_outpipe);
std::cout << "Perl script output:\n" << PerlOutput << "\n"; //Huh? It's empty!
std::cout << "length of perl's output: " << PerlOutput.length() << "\n";
perl の出力はバッファより大きくても大きくなくてもよいので、fgets を呼び出すたびに単にそれを std::string オブジェクトに追加し、perl が出力を終了したらそれを処理します。
しかし、この文字列はすぐに eof に到達するため、何も追加されません。popen に与えたコマンドが間違っているのではないかと最初に考えました。スペース文字が間違った場所などにあるため、popen を呼び出す前に、正確なコマンドをダンプします。このコマンドをターミナル ウィンドウにコピー アンド ペーストし、自分でコマンドを実行すると、期待どおりに動作します。
Executing perl script, command to execute is:
perl scripts/testscript.pl param1=abc param2=123 param3=Nooo!\ not\ Jackson\ 5!
少し読んだ後、1 年前にまったく同じ問題のように聞こえる別の人を見つけました。Perl ではなく PHP など、若干の違いがありました。スクリプトを引数として使用して、インタープリターを呼び出すのではなく、スクリプトを直接呼び出します。そしてCentOS(私はDebianを使用しています)。それ以外は、ほとんど同じように聞こえました...
どうやらその場合は権限の問題でしたが、これは私には当てはまらないようです。
権限は次のとおりです。
rw-r--r-- mumbles mumbles scripts/testscript.pl
rwxr-xr-x root root /usr/bin/perl
私のプログラムは (自分のユーザーとしてではなく) 私として実行されているので、私の権限が必要ですか? 誰もが私のスクリプトを読むことができ、誰もが perl を実行できます。では、スクリプトをそのように呼び出すことができれば、なぜ私の C++ プログラムが呼び出せないのかわかる人はいますか?
私のプログラムの出力(perlがおそらくそのことをした後)
Perl script output:
length of perl's output: 0