我在使用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!
经过一些阅读,I found someone else with what sounded like the exact same problem a year ago。有一些细微的差别,比如PHP而不是Perl。使用脚本作为参数直接调用脚本,而不是调用解释器。和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