I'm having a problem running a perl script from within a C++ program using popen.
As soon as I call fgets, feof will return 1
So far, I have the following code.
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";
The idea is that perl's output may or may not be larger than the buffer, so with each fgets call, I simply append it into an std::string object, and deal with it once perl has finished its output.
But nothing ever gets appended into this string, as it immediately hits an eof. I first thought that maybe the command I was giving to popen might be wrong. Space characters in the wrong place etc, so before calling popen, I dump the exact command. If I copy and paste this command to a terminal window, and run the command myself, it works as expected.
Executing perl script, command to execute is:
perl scripts/testscript.pl param1=abc param2=123 param3=Nooo!\ not\ Jackson\ 5!
After a bit of reading, I found someone else with what sounded like the exact same problem a year ago. There were some slight differences, like PHP instead of Perl. Invoking the script directly, rather than calling the interpreter, with the script as an argument. And CentOS (where I'm using Debian). Other than that, it sounded almost exactly the same...
Apparently in that case it was a permissions issue, but this doesn't appear to be the case with me.
The permissions are:
rw-r--r-- mumbles mumbles scripts/testscript.pl
rwxr-xr-x root root /usr/bin/perl
My program is running as me (not as its own user), so it should have my permissions right? Everyone can read my script, and everyone can execute perl. So, if I can invoke my script that way, can anyone see why my C++ program can't?
My program's output (after perl has supposedly done its thing
Perl script output:
length of perl's output: 0