Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

How to get output system command in Qt C++?



  • Hello,

    I have a "test.exe" that I can use from the command line with the DOS console from Windows 10.
    Example:
    test.exe blue

    returns a return code of 1
    Otherwise, it returns 0.

    I would like to use this "test.exe" by using command line in C ++ Qt and get the output from this command line, but I searched on the internet and I can't find any simple code for it.
    For example, I found:

    QProcess process;
    process.start("test.exe blue");
    process.waitForFinished(-1); // will wait forever until finished
    
    QString stdout = process.readAllStandardOutput();
    QString stderr = process.readAllStandardError();
    

    But the last two lines are bad and don't work.

    Do you have a good example to use command line in C++ Qt and get the value of this command line, please?

    Thanks.


  • Lifetime Qt Champion

    Hi and welcome to devnet,

    You should add error checking. The application you are calling with QProcess may have not started properly or triggered an error.



  • Can you show me an example of code, please?


  • Lifetime Qt Champion

    @tadamo said in How to get output system command in Qt C++?:

    Can you show me an example of code, please?

    It's all in the doc: https://doc.qt.io/qt-5/qprocess.html#details

    And if you want the return code you should take a look at QProcess::exitCode()



  • Thanks, but I can't get the value of exitcode. Here is my code:

    QString program = "test\\test.exe";
    QStringList arguments;
    arguments << "blue";
    
    QProcess *myProcess = new QProcess(this);
    myProcess->start(program, arguments);
    int res = myProcess->exitCode();
    

    I retrieve each time 0 in the varaible res whereas it should be 1.
    Could you fix my code please?

    Thanks.



  • @tadamo
    You need to get the exit code AFTER the process finished.

    Asynchronous (non-blocking) way:

    QProcess *myProcess = new QProcess(this);
    connect(myProcess, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished), this,
         [=](int exitCode, QProcess::ExitStatus exitStatus){
        //use exitCode here directly
    });
    myProcess->start(program, arguments);
    

    Synchronous (blocking) way:

    myProcess->start(program, arguments);
    myProcess->waitForFinished();
    int res = myProcess->exitCode();
    

    Note: you may also need to handle FailedToStart error when "start" or timeout when "waitForFinished"


Log in to reply