Retrieving Information about a Shared Memory Object

You can use the fstat() function to retrieve information about a shared memory object associated with a file descriptor. The fstat() function retrieves only the following members associated with a shared memory from the structure stat declared in <sys/stat.h>:

  • st_uid

  • st_gid

  • st_size

  • st_mode

For more information about the members of the structure stat, see Open Group

Example:

#include <stdio.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <errno.h>
int main(void)
    {
    int fd; //File descriptor
    int ret;
    struct stat buffer; //Stores the data associated with the members of the structure stat
    if((fd = shm_open("page", O_RDWR|O_CREAT, 0666)) < 0)
        {
        printf("Shared memory creation failed with errno %d\n", errno);
        }
    else
        {
        printf("Shared memory creation was successful\n");
        }
    if((ret = fstat(fd,&buffer) < 0)
        {
        printf("fstat() on shared memory failed with errno %d\n", errno);
        }
    else
        {
        printf("fstat() on shared memory succeeded\n");
        printf("mode = %d\n", buffer.st_mode);
        printf("size = %d\n", buffer.st_size);
        }
    //Checks whether the shared memory mode is same as that of a regular file
    if(S_ISREG(buffer.st_mode))
        {
        printf("Test passed");
        }
    else
        {
        printf("Test failed");
        }
    close(fd);//closing the file descriptor
    if((ret = shm_unlink("page")) < 0) 
        {
        printf("Shared memory unlinking failed with errno %d\n", errno);
        }
    else
        {
        printf("Shared memory unlinking was successful\n");
        }
    return ret;
    }

Related concepts