异步检查QProcess是否正确启动

时间:2018-03-24 05:51:02

标签: qt qt5 qprocess

我需要检查流程是否已开始

我发现了this answer 类似的问题,但我的有点不同。

同步

对于同步检查,我可以轻松地做这样的事情:

QProcess process("foo.exe");
if (!process.waitForStarted()) {
    qWarning() << process.errorString();
}

异步

对于异步检查,我可以这样做:

QProcess *process = new QProcess("foo.exe");
connect(process, &QProcess::errorOccurred, [=]() { 
    qWarning() << process->errorString();
});

但是,QProcess::errorOccurred仅在Qt 5.6中引入。

问题

那么如何执行异步检查QProcess是否在 Qt&lt; 5.6

1 个答案:

答案 0 :(得分:2)

根据文档,Qt 5.5及更早版本中有一个信号QProcess::error

  

当过程发生错误时,会发出此信号。该   指定的错误描述了发生的错误类型。

不,QProcess::error就是您所需要的。它包含所有information以检查是否发生错误。

QProcess::FailedToStart 0   The process failed to start. Either the invoked program is missing, or you may have insufficient permissions to invoke the program.
QProcess::Crashed   1   The process crashed some time after starting successfully.
QProcess::Timedout  2   The last waitFor...() function timed out. The state of QProcess is unchanged, and you can try calling waitFor...() again.
QProcess::WriteError    4   An error occurred when attempting to write to the process. For example, the process may not be running, or it may have closed its input channel.
QProcess::ReadError 3   An error occurred when attempting to read from the process. For example, the process may not be running.
QProcess::UnknownError  5   An unknown error occurred. This is the default return value of error().

异步检查,Qt 5.5及更早版本

connect(process, static_cast<void(QProcess::*)(QProcess::ProcessError)>(&QProcess::error),
    [=](QProcess::ProcessError error){ if(error == QProcess::FailedToStart) qDebug() << "Process failed to start"; });

QProcess::error完全符合您的需要。