1

There is something weird when executing popen on Linux. So basically in a much bigger application I have a function called execute that runs a command by using popen and returns its stdout output.

#define CMD "some_command -s"     // This is the command
#define MAX_BUF 1024*6

static std::string execute(const char* cmd) {
        std::string result;
        char buffer[MAX_BUF];

        FILE* pipe = popen(cmd, "r");
        if(!pipe)
                throw -1;

        try{
                while(!feof(pipe)){
                        if(fgets(buffer, MAX_BUF, pipe) != NULL)
                                result += buffer;
                }
        }catch(...){
                pclose(pipe);
                throw;
        }

        pclose(pipe);
        return result;
}

This usually works fine, the problem comes when rebooting the system. If the applications runs as a daemon for a service, if this service is run at boot time the size of the result variable is 0. When doing a service name_of_service restart, which kills and relaunches the application, then it works and the result variable size is the expected one.

Also tried executing system("some_command -s > /tmp/command_out"); before running the popen and the file /tmp/command_out had the expected output. So this is not a race condition in which the some_command dependencies have not been initialized.

UPDATE

Running the command on another terminal at the same time also works. And inside the service, If I change some_command -s for other commands like ls /tmp, then popen does result in some output.

lpares12
  • 3,504
  • 4
  • 24
  • 45

0 Answers0