c++ - 在 Qt Eventloop 启动之前,我的代码如何接收信号

标签 c++ linux qt qt4 qeventloop

我试图理解为什么在我的 QProcess waitForFinished() 和 waitForStarted() 调用可以工作之前,不需要在以下 Qt 4.8 代码中调用 a.exec() 。我知道 a.exec() 启动事件循环,在我看来, waitFor* 插槽需要在继续执行之前接收信号(即 'started()' 或 'finished()' )。如果事件循环尚未启动,怎么会发生这种情况?

waitForStarted() 的文档:

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

代码:

int main(int argc, char *argv[])
{

    QCoreApplication a(argc, argv);

    // Exec the i2c command to get the power button status
    QProcess i2cprocess;
    i2cprocess.start("/usr/bin/i2cget -f -y 1 0x4b 0x45");

    // Wait for it to start
    if(!i2cprocess.waitForStarted())
    {
        qDebug() << "Could not start QProcess to check power button status.";
        exit(-1);
    }

    // Wait for it to finish
    bool returnValue = i2cprocess.waitForFinished();
    if ( returnValue )
    {
        QByteArray status = i2cprocess.readAllStandardOutput().trimmed();
        bool ok;
        quint16 hexValue = status.toUInt(&ok, 16);
        qDebug() << "Power button status: " << status << hexValue << (hexValue & 0x01);

        // We want LSB
        exit(hexValue & 0x01);

    }
    else
    {
        qDebug() << "Error, process never completed to check power button status.";
        exit(-1);
    }

    return a.exec();

}

最佳答案

直接信号槽连接只是间接函数调用,它们与事件循环没有任何关系。

不过,waitForXxxx 方法的作用是旋转一个本地事件循环,直到信号触发。信号从一些代码中触发,操作系统通知进程状态已更改。该代码在功能上由事件循环“执行”。

请记住,在 Qt 中,您可以随心所欲地创建临时事件循环 - 这是一种不好的做法,您永远不应该编写使用 waitFor 方法的代码。它对您的代码提出了通常不存在的要求 - 从而引入了错误!

那么问题来了:在等待进程改变状态时,事件循环有什么用?在内部,流程通知需要等待 native 事件或回调,而这些都从事件循环中得到处理。即使不使用任何事件,事件循环也会执行操作系统向应用程序提供回调所需的可中断 sleep 。

关于c++ - 在 Qt Eventloop 启动之前,我的代码如何接收信号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30506952/

相关文章:

c - C 中是否有一种编程方式来确定 Linux 下一组进程中曾使用过的进程数?

c++ - std::string 无法识别大于 127 的字符

c++ - QT - 如何在 QLineEdit 上应用 QToolTip

c++ - 具有基本身份验证的 HTTPS 客户端的 C/C++ 库

c++ - Linux 共享库被加载两次

c++ - 确定多维数组中的行大小和列大小

c - "fork()"后printf异常

unit-testing - Qt 单元测试设置

c++ - 理解 C++ 中的常量

c++ - 返回引用的 const 方法