如何检查QProcess是否正确执行?

时间:2016-06-22 07:55:33

标签: c++ linux qt

QProcess process_sdcompare;
QString command_sdcompare;
QStringList args_sdcompare;

command_sdcompare = "diff";
args_sdcompare << "Filename" << "Filename";

process_sdcompare.start(command_sdcompare,args_sdcompare,QIODevice::ReadOnly);
process_sdcompare.waitForFinished();                                        
QString StdOut_sdcompare = process_sdcompare.readAllStandardOutput(); //Reads standard output
QString StdError_sdcompare = process_sdcompare.readAllStandardError(); //Reads standard error

if(StdOut_sdcompare.isEmpty())  //the process output is checked here if empty it is a success
    return 1;

我正在运行上面的代码。在比较不相似的文本文件后检查错误情况时,isEmpty()会返回false

如何检查QProcess执行是否没有错误?

4 个答案:

答案 0 :(得分:5)

我使用QProcess::error()查询最后一个错误(用于快速调试),但这是一种“更好”的方法:

// capture any errors (do this before you run the process)
connect(&process_sdcompare, &QProcess::errorOccurred, this, &ThisClass::processError);

然后定义插槽:

ThisClass::processError(QProcess::ProcessError error)
{
    qDebug() << "error enum val = " << error << endl;
}

<强>更新

或者使用Lambda:

// No need to define a slot function...
connect(&process_sdcompare, &QProcess::errorOccurred, [=](QProcess::ProcessError error) 
{ 
    qDebug() << "error enum val = " << error << endl; 
});

答案 1 :(得分:1)

我认为所有状态和错误功能都无法确定流程执行是否成功。例如,尝试执行一个不存在的程序(在Windows下):

error(): QProcess::ProcessError(FailedToStart)
exitStatus(): QProcess::ExitStatus(NormalExit)
exitCode(): 0
errorString(): "Process failed to start: Das System kann die angegebene Datei nicht finden."

如果该过程实际上已成功执行:

error(): QProcess::ProcessError(UnknownError)
exitStatus(): QProcess::ExitStatus(NormalExit)
exitCode(): 0
errorString(): "Unknown error"

所以我认为“未知错误”不是成功的指标。

我认为解决方案如下:

QProcess *m_proc = new QProcess(this);
bool errorOccured = false;
QProcess::ProcessError procError;
QObject::connect(m_proc, &QProcess::errorOccurred, [&](QProcess::ProcessError error)
{
    procError = error;
    errorOccured = true;
});

m_proc->start(...);

答案 2 :(得分:0)

waitForFinished返回时,它会返回一个广泛表示成功的bool。正如Karsten所建议的那样,您可以使用QProcess::exitCode检查实际成功与否。

答案 3 :(得分:0)

这是您使用QProcess

的方法
QProcess process_sdcompare;
QStringList args_sdcompare;
args_sdcompare << "Filename" << "Filename";    
process_sdcompare.setProgram("diff");
process_sdcompare.setArguments(args_sdcompare);
process_sdcompare.start();
if (process_sdcompare.waitForStarted() && process_sdcompare.waitForFinished()) {
  QString StdOut_sdcompare = process_sdcompare.readAllStandardOutput();   
  QString StdError_sdcompare = process_sdcompare.readAllStandardError();

  if(StdOut_sdcompare.isEmpty())
      return 1;
  }
}