wesolyromek
wesolyromek

Reputation: 650

Check POSIX shared memory object size

Is there any way to check if a file descriptor returned by shm_open has been created by current process or existed earlier? Also, after doing so is there any way to check it's size?

This is what I have at the moment:

if ((fd = shm_open(SHARED_OBJ_NAME, O_RDWR|O_CREAT, 0777)) == -1)
    die(1, "Failed to open shared object");

fd_size = lseek(fd, 0, SEEK_END);

printf("Shared size: %ld\n", fd_size);

if (fd_size == -1 || fd_size < SHARED_OBJ_SIZE) {
    if (ftruncate(fd, 255) == -1)
        printf("ftruncate failed\n");
    fd_size = lseek(fd, 0, SEEK_END);
}

printf("Shared size: %ld\n", fd_size);

But the problem is that I'm always getting "Shared size: -1" twice, and ftruncate doesn't fail only if called right after the object has been created.

Upvotes: 5

Views: 3192

Answers (1)

alk
alk

Reputation: 70883

You might want to use stat() on the shared memory's name passing in the address of an instance of struct stat. If the function succeeded you find the shared memory's size in the structures member st_size.

From the POSIX documentation on stat():

If the named file is a shared memory object, the implementation shall update in the stat structure pointed to by the buf argument the st_uid, st_gid, st_size, and st_mode fields, [...]


Also calling lseek() on a shared memory descriptor results in unspecified behaviour, so it might lead to the expected result or not, depending on the platform the code is running on. To keep the code portable, do not do this.

From the POSIX documentation on lseek():

If fildes refers to a shared memory object, the result of the lseek() function is unspecified.

Upvotes: 4

Related Questions