关于qt:QProcess的正确用法

16次阅读

共计 2075 个字符,预计需要花费 6 分钟才能阅读完成。

  在进行编程过程中,常常用到在程序当中调用其它的程序,这就须要用到过程调用,在 QT 中就用到了 QProcess 的进行过程调用,其有 QT 本身的特点,用起来十分不便,与 C ++ 自身的接口不一样,其流程特点如下:

特点 1:须要 waitForStarted,判断程序启动是胜利,还是失败

特点 2:须要 waitForFinished,判断程序是否完结

这也是比拟传统的用法,当然,你不违心判断完结,就能够不判断了。

个别应用时容易犯的谬误,就是间接省略了特点 1 的处理过程,进行了特点 2,失常的话,是没问题,然则被调用的程序出问题的话,那就难查找起因了,如下:

//QProcess 的用法
void MainWindow::on_pushButton_2_clicked()
{qDebug()<<"enter function MainWindow::on_pushButton_2_clicked";
    QProcess myProcess;
    QStringList arguments;
    arguments += "1";
    arguments += "2";
    myProcess.start("./test", arguments);
    myProcess.closeReadChannel(QProcess::StandardOutput);
    myProcess.closeReadChannel(QProcess::StandardError);
    myProcess.closeWriteChannel();

    while(!myProcess.waitForFinished(500))
    {qDebug()<<"wait";
        sleep(2);
        QCoreApplication::processEvents(QEventLoop::AllEvents, 2000);
    }
    qDebug()<<"exit function MainWindow::on_pushButton_2_clicked";}

下面代码看着是没问题的,失常是能够执行的,我专门测试了一个异样的状况,就是下面的./test 程序是不存在的,执行状况如下:

enter function MainWindow::on_pushButton_2_clicked
wait
wait
wait
wait
wait
wait
wait
wait

发现了,程序进入了死循环,你也不晓得什么起因,是不是,有些蒙了

起因是,程序启动就失败了,这时 waitForFinished() 函数会始终返回 false, 官网也有相应的阐明:

Returns true if the process finished; otherwise returns false (if the operation timed out, if an error occurred, or if this QProcess is already finished)

说的很明确,如果过程曾经完结了,会始终返回 false, 所以下面就进入了死循环。
那怎么解决呢?
上面就说说 QProcess 的规范流程了,如下:

//QProcess 的用法
void MainWindow::on_pushButton_2_clicked()
{qDebug()<<"enter function MainWindow::on_pushButton_2_clicked";
    QProcess myProcess;
    QStringList arguments;
    arguments += "1";
    arguments += "2";
    myProcess.start("./test", arguments);
    myProcess.closeReadChannel(QProcess::StandardOutput);
    myProcess.closeReadChannel(QProcess::StandardError);
    myProcess.closeWriteChannel();

    if(myProcess.waitForStarted())
    {qDebug()<<"启动胜利";
    }
    else
    {qDebug()<<"启动失败 error:"<<myProcess.errorString();
        return;
    }

    while(!myProcess.waitForFinished(500))
    {qDebug()<<"wait";
        sleep(2);
        QCoreApplication::processEvents(QEventLoop::AllEvents, 2000);
    }
    qDebug()<<"exit function MainWindow::on_pushButton_2_clicked";}

这样再执行,输入如下:

enter function MainWindow::on_pushButton_2_clicked
启动失败 error: "Process failed to start: 零碎找不到指定的文件。"

这样的话,就晓得谬误了,也不会进入死循环了,这也阐明,如果想得到程序返回的后果,waitForStarted() 与 waitForFinished() 两个函数都不可少。

正文完
 0