Search code examples
c++popen

_popen result in a string : a special case


My purpose of the program is to get the cmd output in a string but there is a strange problem :

string ChangeStatus()
{  status = exec("net stop mysql");
   cout<<status;
   return status;     
}

string exec(char* cmd) 
{
    pipe = _popen(cmd, "r");
    if (!pipe){
        sprintf(returnErrorMSG,"ERROR");
        return returnErrorMSG;
    }

    std::string result = "";
    while(!feof(pipe))
    {
        if(fgets(buffer, 128, pipe) != NULL)
        {
             result +=buffer;
        }
    }
    _pclose(pipe);
    return result;

}

My aim is to catch the output of the command (passed as a parameter to exec function, into a string variable -

Now the problem is Say, mysql is currently running : then if I call the function exec("net stop mysql"), it tries to stop the mysql and give the result in the result string which is returned from the function. The result string contains - "The Mysql service was started successfully" .... it is ok.

But if the mysql is currently running and I call exec("net start mysql"), then it saying "The requested service has already been started" - which is totally justified. My point is this statement should be in the result string in the exec function. This time the result string is simply empty and the exec function returns a empty string. I need that output in the result string.


Solution

  • In your case, the message goes to standard error stream, but popen() handles only standard output. To catch the message, you can use net stop mysql 2>&1 command or implement your version of popen() that will handle both standard output and standard error streams.

    Judging by the fact that you use _popen() instead of popen(), I assume that you may write not for Unix. So first option may not work in your OS.