C mmap Example

(Last Updated On: July 3, 2021)

Index: What’s covered in the article?

 

Introduction:

The world is growing dynamically. Behind this growth, many different technological developments are assisting this world to move fast. The biggest technological device that has made enormous changes in this is the computer. A computer is an electronic device that stores and processes data in the binary system according to the instruction given by the users. The computer is a device that has made impossibilities possible. It is known to be a part of everyone’s daily life now. Besides its usage computer have made life easier and faster too. Moreover, it has achieved a milestone in the history of advancement. We have compiled the best information about example of the c mmap in the article. We suggest you carry on rading.

The computer is used everywhere, whether you are at your home, hospital, office, schools or restaurants you need its assistance. This device aids in making your working easier and comfier than ever before. You can easily audit long reports, make lengthy documents, can safely keep records, and whatnot. Furthermore, its further branches like laptops, smartphones, and tablets are yet another electrical gadget that has become important to almost every individual in this world.

The computer basically operates with the assistance of hardware and software. Hardware is the devices that are visible and are sensed by the physical touch. These devices include all the outer parts of the computer like keyboard, monitor, CPU, mouse, printer, scanner, speaker, etc., and also some internal parts of the computer system like hard disks, floppy disk, hard disk drives, RAM, ROM, graphic cards, Sound cards and motherboard etc., while the software is a set of instruction that is provided to the hardware devices to instruct them what to do and how to do. The software includes browsers, movie players, graphic programs, etc.

Both software and hardware work by proper coordination. But there is a system that mange’s this coordination and it is termed as an operating system. An operating system manages, memory management, handles input and output, controls all the peripheral devices, and coordinates them. The operating system can be of different types depending upon the model of the computer system. Some of the operating systems are Microsoft Windows, Linux, macOS, Solaris, Free BSD, Chrome OS, ubuntu and fedora, etc.

But for the data and information stored inside a computer, you need to encode it. Encoding is a process in which the data and the information are stored in the binary forms inside the computer, and upon the user’s reading, it converts this data into human-readable form. But sometimes, you need memory mapping to store your data in the storage chips, but what is memory mapping? Come let’s discuss it in detail.

 Memory mapping:

Memory mapping is a process in which the data or information or a file is mapped with a particular address in the computer’s memory or application space. Memory mapping is very crucial to access, store and find data or files inside the computer system. when you store any type of data inside your computer memory this data or file is encoded. After encoding, its memory mapping is done which provides this data or file a specific address to store inside the computer storage. So, if you want to access this file in the future you can easily find it in the computer memory due to the fruits of memory mapping.

Memory mapping

Advantages of memory mapping:

Memory mapping is very crucial when we talk about the storage and encoding of any type of data or file. Some of its advantages are discussed as under:

 

  • Faster file accessing: You can easily access files through memory mapping. Files can easily be found by the particular address that has assigned by the computer storage or memory to that specific file. You don’t need to find files or data over your whole computer memory. Memory mapping saves your time and allows faster access.
  • Provides efficiency: Memory mapping allows to provides efficiency in accessing data or files. Memory mapping allocates files or data in a specific order. This specification allows file efficiency and more refurbished storage.
  • Efficient coding: Memory mapping encodes or encrypts data in a more modish manner. Several encoding styles allow your data encryption more efficiently.
  • Easy sharing of memory: Via memory mapping, you can efficiently share or transfer encoded data or information in a refurbished manner. File’s specificity allows better and particular sharing of data and information between different applications as well.

mmap:

mmap is a method of memory mapping. It is one of the components of a POSIX-compliant Unix system that maps the file into the computer or application’s memory. Its contrivance the pages demand as the files are not read directly from the computer memory or the disk drive and do not use the physical RAM directly.

mmap

mmap () is a function that is used for mapping purposes between a process address space and files or device. When a file mapping occurs of a file to a process address space, the data or file can be accessed as an arrangement in the computer program. mmap is considered as one of the most refurbish and efficient ways of encoding and accessing data or files. It provides a data structure that can easily be assessed without abstracting files from reading and writing.

C language:

C programming or a C language is one of the most famous computer languages. C language was first invented in 1972 by Dennis M. Ritchie at the Bell telephone laboratories. The main aim of developing the C language was to develop the UNIX operating system. It is one of the most famous computer programming or language like that of java programming and is widely used by modish software programmers. C language is also studied as a subject when you are aiming to become a professional software engineer. Moreover, it is compulsory for you to learn the C language when you are urged to work in the software development domain.

C language

Advantages of C language:

  • Easy to learn: it is easy to learn a C language program than any other computer language.
  • Handling of activities: it can also handle low-level or moderate level activities allowing you to experience better and finer working.
  • Structure base language: C language is a structured based language. This attribute allows you to learn more efficiently and in an improvised manner.
  • Compilation on computer platforms: C language can be easily compiled to several computer platforms and operating systems too.
  • Produces modish programs: C language allows to design and refurbish modern and efficient computer-based programs and software.

Advantages of C language

Applications of C language:

Firstly, C language was used for operating system development. It was made to encode binary code in the assembly language. But now C language is used for several other purposes that have increased the demand and use of the C language. Some of the applications of the C language are discussed as:

  • In operating systems
  • As language compilers
  • As text editors
  • For mmap encoding
  • As assemblers
  • As print spoolers
  • For network drivers
  • For designing modern programs
  • For designing databases and metadata and for refurbishing it.
  • As a language interpreter
  • For utility purposes etc.,

Applications of C language

As we have discussed that C language is used for multiple purposes, one of its attributes is in the functioning of mmap function as well. the mmap function can be used in a C language supported operating system like that of Linux and UNIX etc., but how mmap functioning can be done by the use of C language? Or how C language helps in the encoding of mmap function? Come let’s discuss this attribute of the C language in detail.

mmap functioning in the C language:

If you want to work in the C language to encode the mmap function, you need to follow some easy steps. These steps are discussed as:

  1. make a header file
  2. draw syntax
  3. use the arguments.

mmap functioning in the C language

  1. Make a header file: for mmap functioning in a C language you need to make a header file first. For such purposes you need to do encoding like:

#include <sys/let’s>

The above-mentioned characters are used to make a header file in the mmap in the C language. The next step is the syntax formation of drawing of syntax.

  1. Draw a syntax:

Once you are done with header file formation. Now you have to enter a specific syntax in the command box. This syntax depends upon the type of data that is encoded by the mmap function. The syntax contains the sequence of characters and letters.

  1. Use of arguments:

Arguments in the programming language are a set of variables, characters, letters, or items that are independent of each other and are used for encoding purposes of a particular file or data.

For mmap encoding of files or data, six types of arguments are being bused in the C language. These arguments are:

  • Address
  • Length
  • Protect
  • Flags
  • Files

Address:  this argument gives a particular starting preferred address for mapping purposes. The address awarded to the particular file or data is different from that of other files and data. Each time the kernel chooses a specific address for mapping. if the address is null then the kernel places the mapped file or data elsewhere or anywhere it fits well.

Length: in mapping, the length is the total number of bytes or the total amount of data that is needed to be mapped. Length indicates the total number of bytes of the mapped file or data.

Protect: This argument involves the permission of accessing the particular mapped data or file. This argument controls the access permissions of the mapped data.

Flags: The nature of the mapped data or file is controlled by this argument. The nature of the mapped data can be classified according to this argument is of four types:

  • MAP_PRIVATE
  • MAP_ANONYMOUS/MAP_ANON
  • MAP_FIXED

Filedes: This argument is the file descriptor. This argument is encoded for the mapping of the file descriptor.

Offset: This is the argument form where the mapping initiates. The offset argument helps in opening the file descriptor, the filedes argument.

Example of the c mmap:

The example program for c language mmap function call is given as under:

Example#01: allocation of memory:

#include <stdio.h>
#include <sys/mman.h>

int main(){

int N=5;
int *ptr = mmap ( NULL, N*sizeof(int),
PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, 0, 0 );

if(ptr == MAP_FAILED){
printf(“Mapping Failed\n”);
return 1;
}

for(int i=0; i<N; i++)
ptr[i] = i*10;

for(int i=0; i<N; i++)
printf(“[%d] “,ptr[i]);

printf(“\n”);
int err = munmap(ptr, 10*sizeof(int));
if(err != 0){
printf(“UnMapping Failed\n”);
return 1;
}

return 0;
}

In this example we have used MAP_PRIVATE, MAP_ANONYMOUS and PROT_WRITE, PROT_READ

Example#02: file reading or reading file:

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

int main(int argc, char *argv[]){

if(argc < 2){
printf(“File path not mentioned\n”);
exit(0);
}

const char *filepath = argv[1];
int fd = open(filepath, O_RDONLY);
if(fd < 0){
printf(“\n\”%s \” could not open\n”,
filepath);
exit(1);
}

struct stat statbuf;
int err = fstat(fd, &statbuf);
if(err < 0){
printf(“\n\”%s \” could not open\n”,
filepath);
exit(2);
}

char *ptr = mmap(NULL,statbuf.st_size,
PROT_READ|PROT_WRITE,MAP_SHARED,
fd,0);
if(ptr == MAP_FAILED){
printf(“Mapping Failed\n”);
return 1;
}
close(fd);

ssize_t n = write(1,ptr,statbuf.st_size);
if(n != statbuf.st_size){
printf(“Write failed”);
}

err = munmap(ptr, statbuf.st_size);

if(err != 0){
printf(“UnMapping Failed\n”);
return 1;
}
return 0;
}

In this example we have first created the file and then mapped the file by this method.

Example#03 file writing:

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

int main(int argc, char *argv[]){

if(argc < 2){
printf(“File path not mentioned\n”);
exit(0);
}

const char *filepath = argv[1];
int fd = open(filepath, O_RDWR);
if(fd < 0){
printf(“\n\”%s \” could not open\n”,
filepath);
exit(1);
}

struct stat statbuf;
int err = fstat(fd, &statbuf);
if(err < 0){
printf(“\n\”%s \” could not open\n”,
filepath);
exit(2);
}

char *ptr = mmap(NULL,statbuf.st_size,
PROT_READ|PROT_WRITE,
MAP_SHARED,
fd,0);
if(ptr == MAP_FAILED){
printf(“Mapping Failed\n”);
return 1;
}
close(fd);

ssize_t n = write(1,ptr,statbuf.st_size);
if(n != statbuf.st_size){
printf(“Write failed\n”);
}

// Reverse the file contents
for(size_t i=0; i \n”);
n = write(1,ptr,statbuf.st_size);
if(n != statbuf.st_size){
printf(“Write failed\n”);
}

err = munmap(ptr, statbuf.st_size);

if(err != 0){
printf(“UnMapping Failed\n”);
return 1;
}
return 0;
}

In this example, the file is first to read and is then written.

Final verdict:

The mmap functioning is purely supported by the Linux operating system. In this article, we have mentioned several attributes of memory mapping. Along with these features, the basic concept of mmap and a brief introduction of C language has also been mentioned. Some examples are also been discussed to elaborate how C language supports mmap functioning.

 

Recommended Readings (visualrsoftware)

Leave a Reply

Your email address will not be published. Required fields are marked *