【问题标题】:QSharedMemory inconsistent behaviour in WindowsWindows 中的 QSharedMemory 不一致行为
【发布时间】:2012-10-29 11:03:14
【问题描述】:

我在玩QSharedMemory,我不确定我是刚刚发现了一个严重的错误还是我做错了什么。案例是文档说如果不存在具有相同键的内存,QSharedMemory::create() 应该返回 true,否则它应该返回 false,并且应该检查 QSharedMemory::error() 以查看发生了什么。

我当前的代码是:

QSharedMemory sm("smtest");
sm.setKey("smtest"); // <--- not needed as I already set the key in the initializator, but I'm leaving it anyways, just for the test
qDebug() << sm.create(1);
qDebug() << sm.create(1); //<--- I expect this to return false, but it returns true.
qDebug() << sm.error(); //<--. I expect this to return QSharedMemory::AlreadyExists, but QSharedMemory::NoError is returned instead.
//wtf?!

我的问题是:我是刚刚在 Qt4 中发现了一个非常大的错误还是我做错了什么?

PS:此代码在 Windows 7 x64 上运行

编辑:为了清楚起见,如果我运行该代码两次,第二个应用程序应该检测到第一个应用程序,但它没有。

编辑 2:我在这里报告了一个错误 https://bugreports.qt.io/browse/QTBUG-27744

【问题讨论】:

  • 这只是一个猜测,文档没有说,但似乎从同一个线程多次调用 create 会返回 true...你为什么要从同一个线程多次调用它还是?
  • @hyde 这只是一个测试。无论如何,如果我两次运行相同的应用程序,我会得到相同的结果。

标签: c++ qt qt4 shared-memory


【解决方案1】:

这绝对是一个错误,请阅读我的错误报告https://bugreports.qt.io/browse/QTBUG-27765

我最近附加了一个补丁来解决这个问题。如果你想解决这个问题,你需要投票。

【讨论】:

  • 今天问题有变! :)
【解决方案2】:

我只是在 Linux 上运行它:

#include <QCoreApplication>
#include <QSharedMemory>
#include <QDebug>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    QSharedMemory sm("smtest");
    sm.setKey("smtest"); // <--- not needed as I already set the key in the initializator, but I'm leaving it anyways, just for the test
    qDebug() << sm.create(1);
    qDebug() << sm.create(1); //<--- I expect this to return false, but it returns true.
    qDebug() << sm.error(); //<--. I expect this to return QSharedMemory::AlreadyExists, but QSharedMemory::NoError is returned instead.
    //wtf?!
    return 0;
}

第一次运行得到

true
false 
4 

可能是您没有创建 QCoreApplication 吗?很多 Qt 的东西往往依赖于被创建的东西。

编辑:强调一下,以上仅在首次运行时发生。后续运行总是给出 false-false。

Edit2:在 Windows 上,结果对我来说也是正确的。

Edit3:似乎是一个错误,听起来很像这样:https://bugreports.qt.io/browse/QTBUG-5123

【讨论】:

  • 为了确保我没有搞砸什么,我将您的代码复制/粘贴到 QtCreator 中,然后我得到了true, true, 4(所以,它一直在某个地方出现问题)。
  • 实际上,我只在第一次运行时得到它。删除文件(由sm.nativeKey() 报告)并再次运行仍然给出假错误。更改键名会再次为第一次运行提供真假。
  • 是的,事实是,由于某种原因,Qt 在每个 .create() 之后返回 true,无论该键是否已经存在。
  • 这也可能是 Windows 功能,不一定是错误...共享内存的实际工作方式取决于系统(正如文档中所解释的那样,尽管它没有解释这一点行为)。在那种情况下,我会说它仍然是一个文档错误。
  • 嗯......这很糟糕......有没有办法检测是否已经有这个键的共享内存?
猜你喜欢
  • 2011-06-15
  • 1970-01-01
  • 2015-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-01
相关资源
最近更新 更多