我的此功能负责创建共享内存段。如您所见,如果此键已经存在共享内存,我将检查EEXIST。由于我使用相同的键定期执行程序,因此该共享内存在第一次执行程序后就存在。

作为测试,我尝试通过shmat()直接访问共享内存。但是无论出于什么原因,它都会失败。这是控制台的输出:

Shared memory with Key 4661 already exists, continue...
Failed to obtain `Shared Memory`: Invalid argument

这是功能:
#define SHM_KEY 0x1235
int create_shrd_memory(uint64_t size) {
    const int shmid = shmget(SHM_KEY, size, IPC_CREAT | IPC_EXCL);
    if(shmid == -1) {
        if(errno == EEXIST) {
            printf("Shared memory with Key %d already exists, continue...\n", SHM_KEY);
            char *shdmem = shmat(SHM_KEY, NULL, 0);
            if(shdmem == -1) {
                fprintf(stderr, "Failed to obtain `Shared Memory`: %s\n", strerror(errno));
            }
            shmdt(shdmem);
            return SHM_KEY;
        } else {
            fprintf(stderr, "Failed to obtain Shared Memory: %s\n", strerror(errno));
            perror("shmget");
            exit(1);
        }
    }

    return shmid;
}

如果我忘记一次打电话给shmdt(),您知道会发生什么吗?这会导致此错误吗?

最佳答案

shmat的第一个参数是shmget的返回值,您正在混合key和id。

您的代码应类似于:

int create_shrd_memory(uint64_t size) {
    int shmid = shmget(SHM_KEY, size, IPC_CREAT | IPC_EXCL);
    if(shmid == -1) {
        if(errno == EEXIST) {
            printf("Shared memory with Key %d already exists, continue...\n", SHM_KEY);

            shmid = shmget(SHM_KEY, size, 0);

            char *shdmem = shmat(shmid, NULL, 0);
            if(shdmem == -1) {
                fprintf(stderr, "Failed to obtain `Shared Memory`: %s\n", strerror(errno));
            }
            shmdt(shdmem);
            return SHM_KEY;
        } else {
            fprintf(stderr, "Failed to obtain Shared Memory: %s\n", strerror(errno));
            perror("shmget");
            exit(1);
        }
    }

    return shmid;
}

关于c - Linux C : Accessing shared memory fails with `Invalid Argument` even though it was just created,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60504242/

10-09 08:48