Qt: How to catch an error with a system call?

I create a GUI application where I make a system call and call gnuplot to run the script. Now I want to create an error message that says that something is wrong (for example, gnuplot is not installed or is in the wrong path).

So, I was thinking about the simplicity of the QMessageBox, but I don't know how I can check if the system call succeeded or not.

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

My system call is as follows:

 system(gnuplot script.txt); 

Any suggestions?

+6
source share
1 answer

You should use QProcess , not a low level system call, because it is a good abstraction in the Qt code base. Otherwise, you will come across specific platform bits. QProcess already solves this for you. If you feel good with a blocking approach, aka. sync, you can write something like this code below.

 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; } 

If you do not want to block while the gnuplot script is running, you can connect a slot or just a lambda from C ++ 11 onwards to readyRead () . Of course, you will also need to connect to the error () signal. The code without lambda for working with pre C ++ 11 environments would look something like this:

 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); } } 
+7
source

All Articles