Search code examples
c++command-lineprocesspocopoco-libraries

Using Poco ProcessHandle to send commands and get the result is getting exception


I am trying to send a simple commands such as "dir" in Windows via Poco's ProcessHandle and get the result from it in C++. But it is not able to return me anything, I'm getting exceptions ("System exception") from the code below. I have similar usage of the ProcessHandle but it is usually about opening an .exe file and passing arguments to it. But now, I just want to send a simple command. Is there anything wrong with the code below? I am doing it in windows currently

I am referring to the code at here

Poco::Process::Args args;
string command = "dir";

Poco::Pipe outPipe;
Poco::ProcessHandle ph(Poco::Process::launch(command, args, 0, &outPipe, 0));

Poco::PipeInputStream istr(outPipe);

std::string s;
int c = istr.get();
while (c != -1) {
    s += (char)c;
    c = istr.get();
}
std::cout << "string is " << s << std::endl;

Solution

  • I found the answer. It seems that I just have to do something like this:

    Poco::Process::Args args;
    args.push_back("/c");
    args.push_back("dir");
    string command = "cmd.exe";
    
    Poco::Pipe outPipe;
    Poco::ProcessHandle ph(Poco::Process::launch(command, args, 0, &outPipe, 0));
    
    Poco::PipeInputStream istr(outPipe);
    
    std::string s;
    int c = istr.get();
    while (c != -1) {
        s += (char)c;
        c = istr.get();
    }
    std::cout << "string is " << s << std::endl;