Featured Post

Trie implementation in C

IPC Memory Map implementation in C

Using memory mapped file two processes can both open the same file and both read and write from it, thus sharing the information.It is easier to map a section of the file to memory, and get a pointer to it rather than doing fseek .

A memory mapped file is very easy to use as we can perform simple arithmetic operations to get and set data from a file.

Here is a simple example of creating and using memory mapped files.It takes a file and offset as input and tells what data is present at that offset.


//memorymap.c
//To compile : gcc -o mmap memorymap.c
//To run : ./mmap file-name offset

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/mman.h>

#include <sys/stat.h>
#include <errno.h>
int main(int argc, char *argv[])
{
    int fd, offset;
    char *data;
    struct stat sbuf;
    if (argc != 3)
    {
        fprintf(stderr, "usage: %s <file-name> offset\n",argv[0]);
        exit(1);
    }
    if ((fd = open(argv[1], O_RDONLY)) == -1)
    {
        perror("open");
        exit(1);
    }
    /*argv[1] is the file name to be examined*/
    if (stat(argv[1], &sbuf) == -1)
    {
        perror("stat");
        exit(1);
    }
    offset = atoi(argv[2]);
    if (offset < 0 || offset > sbuf.st_size-1)
    {
        printf("%s: offset must be in the range 0-%d\n",argv[0],sbuf.st_size-1);
        exit(1);
    }
    data = mmap((caddr_t)0, sbuf.st_size, PROT_READ, MAP_SHARED, fd, 0);
    {
        if (data == (caddr_t)(-1))
        {
            perror("mmap");
            exit(1);
        }
        printf("Byte at offset %d is '%c'\n", offset, data[offset]);
        return 0;
    }
}

Comments

Post a Comment

Please post your valuable suggestions