Linux C: Accessing shared memory fails with `Invalid Argument` even though it was just created

北城余情 提交于 2021-01-27 20:01:20

问题


This function of mine is responsible for creating a shared memory segment. As you can see, I check for EEXIST in case there already is a shared memory with this key. As I am executing the program regularly with the same key, this shared memory exists after the first program execution.

As a test, I try to access the shared memory directly afterwards via shmat(). But for whatever reason, it fails. This is the output of the console:

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

This is the function:

#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;
}

Do you know what happens, if I forgot one time to call shmdt()? Can this lead to this error?


回答1:


shmat first argument is the return value of shmget, you are mixing key and id.

You code should be something like:

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;
} 


来源:https://stackoverflow.com/questions/60504242/linux-c-accessing-shared-memory-fails-with-invalid-argument-even-though-it-wa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!