Search code examples
cunixposixshared-memory

Can't define the size of a shared memory object


Hello I'm trying to create a shared memory object using POSIX functions but I'm getting a weird error.

// Create shared memory

if( (shmid = shm_open("/OS",   O_CREAT ,0700)) == -1){
    printf("Error creating memory\n");
    exit(1);
}
printf("shmid: %d\n", shmid);

if (ftruncate(shmid, sizeof(int)) == -1){
    printf("Error defining size\n");
    exit(1);
}

As you can imagine it keeps printing out "Error defining size". The value printed out by shmid is 3, a valid value. Yet the ftruncate() functions returns -1 because of an error... the value set to errno is 22 which as I have seen on the internet is due to "invalid arguments" but I don't understand why.... suggestions?


Solution

  • The errno value of 22 on a Linux system is EINVAL. Instead of showing the number value you should use perror or strerror(errno) to get a text error message like "Invalid argument".

    Use

    if ((shmid = shm_open("/OS", O_RDWR | O_CREAT, 0700)) == -1){
    

    The POSIX documentation for ftruncate() lists:

    [EBADF] or [EINVAL] — The fildes argument is not a file descriptor open for writing.

    and

    [EINVAL] — The fildes argument references a file that was opened without write permission.

    The Linux man page at https://linux.die.net/man/2/ftruncate states

    EBADF or EINVAL — fd is not open for writing.