使用 QSharedMemory 附加现有的共享内存

Attach existing Shared Memory with QSharedMemory

在应用程序 1(C 代码)中,我正在创建这样的共享内存:

char * key_path = "/tmp/shmem";

int file = open(key_path, O_CREAT | O_RDWR | O_APPEND, 0755);
close(file);
key_t key = ftok(key_path, 1);

shmid = shmget (key, SHM_DATASIZE , IPC_CREAT | SHM_R | SHM_W);
shmdata = shmat(shmid, NULL, 0);shmid);

在应用程序 2(QT) 中,我想访问此 SharedMemory

const char* native_key = "/tmp/shmem";

key_t ft_key = ftok(native_key, 1);
key = QString::number(ft_key);

QSharedMemory shmem(key);
if(!shmem.attach()) {
    qDebug() << "attach failed" << shmem.errorString()  << shmem.key() << shmem.nativeKey() << endl;
}

attach failed "QSharedMemory::attach (shmget): doesn't exist" "16858191" "/tmp/qipc_sharedmemory_24384b85e5d54b23bd4f84f14de71b10d4801666"

所以我尝试了以下方法

const char* native_key = "/tmp/shmem";

key_t ft_key = ftok(native_key, 1);
key = QString::number(ft_key);

QSharedMemory shmem(key);
shmem.setNativeKey(native_key);
if(!shmem.attach()) {
    qDebug() << "attach failed" << shmem.errorString()  << shmem.key() << shmem.nativeKey() << endl;
}

attach failed "QSharedMemory::attach (shmget): doesn't exist" "" "/tmp/shmem_prot"

我查看了 qsharedmemory_unix.cpp

的来源

我认为问题在于未设置 unix_key,因此 attach() 中的 shmget 将失败。 handle() 是私有的,所以我不能调用这个函数来设置 unix_key.

是否可以在不知道共享内存大小/调用 create() 的情况下访问共享内存?

当我尝试调用 create() 时

QSharedMemory shmem(key);
shmem.create(SHM_DATASIZE);

将创建一个新的共享内存...

我做错了什么?提前致谢。

您访问的不是同一个共享内存段。 Qt 修改你传递给它的键,结果是一个不同的键,因此共享内存 id。

Per the QSharedMemory documentation:

Warning: QSharedMemory changes the key in a Qt-specific way, unless otherwise specified. Interoperation with non-Qt applications is achieved by first creating a default shared memory with QSharedMemory() and then setting a native key with setNativeKey(). When using native keys, shared memory is not protected against multiple accesses on it (for example, unable to lock()) and a user-defined mechanism should be used to achieve such protection.

您似乎需要使用 QSharedMemory 创建共享内存段,使用 setNativeKey() 设置新密钥,然后从 QSharedMemory 外部附加到该内存。