Writing, Reading and Seeking from a Shared Memory

Use the write() function to write to shared memory

Use the read() function to read data from shared memory.

Use the lseek() function to set the file offset associated with a shared memory file descriptor

Example:

      
       
      
      #include <stdio.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
int main(void)
    {
    int fd; //File descriptor
    int ret = 0;
    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 = write(fd, "symbian", 7)) < 0)
        {
        printf("Writing into shared memory failed with errno %d\n", errno);
        }
    else
        {
        printf("Writing into shared memory was successful\n");
        }
    if((ret = lseek(fd, -6, SEEK_END)) < 0)
        {
        printf("Seeking from end failed with errno %d\n", errno);
        }
    else
        {
        printf("lseek was successful\n");
        }
    char buf[7];
    if((ret = read(fd, (void*)buf, 6)) < 0)
        {
        printf("Reading from shared memory failed with errno %d\n", errno);
        }
    else
        {
        printf("Reading from shared memory was successful\n");
        printf("Buffer read = %s\n", buf);
        }
    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;
    }