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

binaryBigInt :

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?

Mathieu :

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=21716&siteId=1