【问题标题】:Asynchronous check if QProcess started correctly异步检查 QProcess 是否正确启动
【发布时间】:2018-03-24 05:51:02
【问题描述】:

我需要检查进程是否开始正确。

我在网上找到了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 中正确启动?

【问题讨论】:

  • QProcess::errorOccurredQProcess::error基本相同。那为什么你的不一样?如果你解释它,我会修改或删除我的答案。

标签: qt qt5 qprocess


【解决方案1】:

根据文档,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 完全满足您的需求。

【讨论】: