gpt4 book ai didi

qt - 可靠检测 QProcess 精加工

转载 作者:行者123 更新时间:2023-12-02 00:33:58 25 4
gpt4 key购买 nike

我有一个 Windows Qt 应用程序,它使用 QProcess 来运行可能需要也可能不需要输入的外部程序。如果需要,输入始终y,后跟ENTER。并且,如果输入 y,程序将立即退出。

所以我在代码中采取的操作是:

QProcess process;
QString cmd = QString("myprog.exe %1").arg(myParam);

process.start(cmd);
if (! process.waitForStarted(10000))
{
logError("Timed out starting preparation!");
return;
}
process.write("y\n");
if (! process.waitForFinished(5000))
{
process.kill();
process.waitForFinished(5000);
logError("Timed out finishing preparation!");
return;
}

现在我经常会看到最终的错误消息尽管事实上该过程似乎工作正常(在事件发生后可以检测到输入y,所以我知道它是发生)。这是间歇性的。

调查让我找到了 Qt QProcess doco,它有这个 gem :

bool QProcess::waitForFinished(int msecs = 30000)

Blocks until the process has finished and the finished() signal has been emitted, or until msecs milliseconds have passed.

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).

怀疑可能是最后一句话刺痛了我。由于该进程在您输入 y 后立即退出,因此我认为当我到达第一次调用 WaitForFinished() 时它就不再存在了。因此该函数将返回 false,并且我假设它无法正常工作。

因此我有两个问题。首先我的理解正确吗?进程是否有可能在检查之前退出,从而导致错误的返回值。

其次,如果是这种情况,您如何区分在检查之前已退出的进程和在超时开始之前尚未退出的进程之间的区别?

最佳答案

当您在调用waitForFinished()时认为进程已经关闭时,您应该检查进程是否正在运行。

process.write("y\n");
process.waitForFinished(5000)
if(process.state() != QProcess::NotRunning)
{
..
}

关于qt - 可靠检测 QProcess 精加工,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47787407/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com