Command working in terminal, but not via QProcess

前端 未结 3 1945
一整个雨季
一整个雨季 2020-11-30 07:48
ifconfig | grep \'inet\'

is working when executed via terminal. But not via QProcess

My sample code is

QProcess p1;
p1.star         


        
相关标签:
3条回答
  • 2020-11-30 08:07

    The QProcess object does not automatically give you full blown shell syntax: you can not use pipes. Use a shell for this:

    p1.start("/bin/sh -c \"ifconfig | grep inet\"");
    
    0 讨论(0)
  • 2020-11-30 08:11

    QProcess executes one single process. What you are trying to do is executing a shell command, not a process. The piping of commands is a feature of your shell.

    There are three possible solutions:

    Put the command you want to be executed as an argument to sh after -c ("command"):

    QProcess sh;
    sh.start("sh", QStringList() << "-c" << "ifconfig | grep inet");
    
    sh.waitForFinished();
    QByteArray output = sh.readAll();
    sh.close();
    

    Or you could write the commands as the standard input to sh:

    QProcess sh;
    sh.start("sh");
    
    sh.write("ifconfig | grep inet");
    sh.closeWriteChannel();
    
    sh.waitForFinished();
    QByteArray output = sh.readAll();
    sh.close();
    

    Another approach which avoids sh, is to launch two QProcesses and do the piping in your code:

    QProcess ifconfig;
    QProcess grep;
    
    ifconfig.setStandardOutputProcess(&grep); // "simulates" ifconfig | grep
    
    ifconfig.start("ifconfig");
    grep.start("grep", QStringList() << "inet"); // pass arguments using QStringList
    
    grep.waitForFinished(); // grep finishes after ifconfig does
    QByteArray output = grep.readAll(); // now the output is found in the 2nd process
    ifconfig.close();
    grep.close();
    
    0 讨论(0)
  • 2020-11-30 08:29

    You can not use the pipe symbol in QProcess it seems.

    However there is the setStandardOutputProcess Method that will pipe the output to the next process.

    An example is provided in the API.

    0 讨论(0)
提交回复
热议问题