简体   繁体   中英

Is QProcess::finished emitted if the child process crashes?

该文档说,如果子进程崩溃,将发出error()信号,但是也会发出finished() ,还是仅在成功退出时才发出信号?

Yes. And it returns you status, as docs state:

void QProcess::finished ( int exitCode, QProcess::ExitStatus exitStatus ) [signal]

QProcess::NormalExit    0   The process exited normally.
QProcess::CrashExit 1   The process crashed.

You can find out by testing it. Write a small program that does a NULL pointer dereference (this will guarantee a crash):

struct Foo {
    int a;
};

int main()
{
    Foo* foo = 0;
    int d = foo->a;
}

Make sure you build without optimization so that the dereference doesn't get optimized out. Then run it in a QProcess and check whether finished() is being emitted.

The answer to the question is, as other have noted, "Yes."

And that feels like a problem to me because without a reference to the object that emitted the signals you have to do something like:

void on_finished( int exitCode, QProcess::ExitStatus exitStatus )
{
    if ( existStatus == QProcess::CrashExit )
    {
        // We'll handle in on_errorOccured()
        return;
    }

    // ...
}


void on_errorOccured( QProcess::ProcessError error )
{
    // ...
}

As an alternate to accepting I wrote a thin wrapper class that connects (only!) to QProcess::stateChanged(QProcess::ProcessState newState) and works out what happened using newState and calling the QProcess object:

void ProcessWrapper::on_stateChanged(QProcess::ProcessState newState)
{
    switch (newState)
    {
    case QProcess::Starting:
        // No action needed
        break;
    case QProcess::Running:
        emit( started( this ) );
        break;
    case QProcess::NotRunning:
        if ( m_process.exitStatus() != QProcess::NormalExit )
            emit( crashed( this, m_process.error() ) );
        else
            emit( finished( this, m_process.exitCode() ) );
        break;
    }
}

The signals the wrapper emits have two properties:

  • Only one signal is emitted when a process ends, and which one tells you how it ended (normally or abnormally).
  • Each signal includes both a code for how things did and a pointer to the object so that the user can inquire further.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM