gpt4 book ai didi

c++ - Qt:如何通过系统调用捕获错误?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:27:36 25 4
gpt4 key购买 nike

我正在构建一个 GUI 应用程序,我在其中执行系统调用并调用 gnuplot 来运行脚本。现在我想构建一条错误消息,指出出现问题时(例如,未安装 gnuplot 或路径错误)。

所以我一直在考虑只放一个QMessageBox,但我不知道如何检查系统调用是否成功。

if(//System call didn't work)
{
QMessageBox msgBox;
msgBox.setWindowTitle("Error");
msgBox.setIcon(QMessageBox::Critical);
msgBox.setText("GNUPLOT was not installed");
msgBox.exec();
}

我的系统调用是这样的:

system(gnuplot script.txt);

有什么建议吗?

最佳答案

你应该使用 QProcess而不是低级系统调用,因为它是 Qt 代码库中的一个很好的抽象。否则,您最终将处理特定于平台的位。 QProcess 已经为您解决了这个问题。如果您碰巧对阻塞方法没问题,又名。 sync,你可以写类似下面的代码。

QProcess process;

process1.start("gnuplot arg1 arg2 etc");

// Wait for it to start
if(!process.waitForStarted())
return 0;

bool retval = false;
QByteArray buffer;
while ((retval = process.waitForFinished()));
buffer.append(process.readAll());

if (!retval) {
qDebug() << "Process 2 error:" << process.errorString();
msgBox.setText(buffer);
return 1;
}

如果你不想在你的 gnuplot 脚本运行时阻塞,你可以连接一个插槽,或者简单地使用 C++11 和更高版本的 lambda,到 readyRead()信号。当然,您还需要连接到 error()信号。在 C++11 之前的环境中使用 lambda 的代码看起来像这样:

GnuPlotReader::GnuPlotReader(QQProcess *process, QObject *parent)
: QObject(parent)
, m_process(process)
, m_standardOutput(stdout)
{
connect(m_process, SIGNAL(readyRead()), SLOT(handleReadyRead()));
connect(m_process, SIGNAL(error(QProcess::ProcessError)), SLOT(handleError(QProcess::ProcessError)));
connect(&m_timer, SIGNAL(timeout()), SLOT(handleTimeout()));

m_timer.start(5000);
}

GnuPlotReader::~GnuPlotReader()
{
}

void GnuPlotReader::handleReadyRead()
{
m_readData = m_process->readAll();

if (!m_timer.isActive())
m_timer.start(5000);
}

void GnuPlotReader::handleTimeout()
{
if (m_readData.isEmpty()) {
m_standardOutput << QObject::tr("No data was currently available for reading from gnuplot") << endl;
} else {
m_standardOutput << QObject::tr("GnuPlot successfully run")<< endl;
}

}

void GnuPlotReader::handleError(QProcess::ProcessError processError)
{
if (processError == QProcess::ReadError) {
m_standardOutput << QObject::tr("An I/O error occurred while reading the data, error: %2").arg(m_process->errorString()) << endl;
messageBox.setText(m_readData);
}
}

关于c++ - Qt:如何通过系统调用捕获错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20839500/

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