Incorrect output from popen

Hi ,

i am using following code to execute shell commands (using popen).
std::string exec(const char* cmd) {
char buffer[128] = {0};
std::string result = "";
FILE* pipe = popen(cmd, "r");
if (!pipe) throw std::runtime_error("popen() failed!");
try {
while (!feof(pipe)) {
if (fgets(buffer, 128, pipe) != NULL)
{
result += buffer;
}
}
} catch (...) {
pclose(pipe);
throw;
}
pclose(pipe);
return result;
}
exec("echo -n $?PATH");

o/p :- 0PATH (even if PATH variable exists).

Can any one explain.
> echo -n $?PATH
$? will give you the exit status of the last command executed.
PATH will print PATH, you are not accessing any variable there.

You could at least try the commands on a terminal first.
HI ne555,

Actually in c shell 'echo $?varName' will give existence of environmental variable .
But popen using bash shell to execute commands .

And I found that there isn't a way to differentiate 'variable having value nothing ' to 'undefined variable' , both are same in bash (please let me know if any thing wrong).

Currently I am using getenv to check variable existence and it's working fine.

Thank you,
Balu Soutani.
Topic archived. No new replies allowed.