WWW Geeksforgeeks Org Memory Mapping Amp

Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

GEEKSFORGEEKS

Memory Mapping
Modern computers have a virtual memory that is not physically present. We can achieve it by setting up a Hard
disk, this way extended memory is called virtual memory. So any program that is inside the computer will have a
virtual memory address to store data. This data cannot be used unless it is converted to a physical address. So, In
short, Memory Mapping is the process done by the Operating System to translate Virtual memory addresses to
physical addresses. So, the program can run anytime when the OS loads it as it is required.

What is Memory Mapping?


Memory mapping or mmap() is a function call in an Operating system like Unix. It is a low-level language, and it
helps to directly map a file to the currently executing process’s own memory address space. Which could optimize
File I/O operations, inter-process communication, etc.

Types of Mapping

1. File Mapping: It will map the File to the process virtual memory

Read-Only Mappings: The File is mapped into memory only for the purpose of reading. If we try to write it will
end up in a segmentation fault.
Read-Write Mappings: The file is mapped into memory for both reading and writing. ie, it helps with file
manipulation.

2. Anonymous mapping: It is a memory-mapped region where there is no connection with any file/device. Or we
can say it is used for dynamic allocation of memory within a program.

Private Anonymous Mapping: This is an area of memory that does not have a file associated with it. It is
commonly used for dynamic allocation. Custom memory allocators are examples of this type of mapping.
Shared Anonymous mapping: Inter-process communication is a type of shared mapping in which multiple
processes can have access to and change the data. An example of this is implementing Inter-process
communication (IPC).

3. Device Mapping: In this type, Registers, hardware devices like graphic cards, and network adapters can be
mapped into the process’s address space.

Implementation of Memory-Mapping Algorithm


Memory mapping involves a series of steps. An algorithmic explanation of how memory mapping can be
implemented in C is provided here:

1. Start
2. Initialize the size of the file and mapping.
3. If the file not exists, create file; Open the file.
4. If exists, truncate the file to the desired size.
5. Create a memory-mapped region.
6. Initialize memory-mapped region with some data.
7. Read and print the contents of the memory mapped region.
8. Un-map the memory and close the file.
9. Stop

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

int main()
{
const char* file_path = "GFG-M-Mapping.txt";
const size_t file_size
= 4096; // Initializing file size to $kb.

// We open the file for read/write operation


int fd = open(
file_path, O_RDWR | O_CREAT,
0400 | 0200); // Use octal values for permissions
if (fd == -1) {
perror("open");
return 1;
}

// if already exist,we trucate it to desired size


if (ftruncate(fd, file_size) == -1) {
perror("ftruncate");
close(fd);
return 1;
}

// Create a memory-mapped region for the file.


void* file_memory
= mmap(NULL, file_size, PROT_READ | PROT_WRITE,
MAP_SHARED, fd, 0);
if (file_memory == MAP_FAILED) {
perror("mmap");
close(fd);
return 1;
}

// Initialize the memory-mapped region with some data.


const char* message
= "Hello Geeks,Memory mapping is done !";
strncpy(file_memory, message, strlen(message));

// Read and print the contents of the memory-mapped


// region.
printf("Contents of the memory-mapped region: %s\n",
(char*)file_memory);

// Unmap the memory and close the file.


munmap(file_memory, file_size);
close(fd);

return 0;
}

Output

Contents of the memory-mapped region: Hello Geeks,Memory mapping is done !

FAQs on Memory Mapping in OS


Q.1: What is Memory mapping in OS?

Answer:

Memory mapping or mmap() is a function call thats helps to directly map a file to the currently executing
process’s own memory address space.

Q.2: What are the types of memory mapping?

Answer:

1. File Mapping: It will map the File to the process virtual memory.

-Read only Mappings

-Read-Write Mappings

2. Anonymous mapping: It is a memory mapped region where there is no connection with any file/device.
Or we can say it is used for dynamic allocation of memory within a program.

Q.3: What are the functions used for memory mapping and un-mapping?

Answer:

mmap() and munmap()

Article Tags : Operating Systems


Read Full Article

Company Explore Languages DSA Data Science & Web


About Us Job-A-Thon Hiring Python Data Structures ML Technologies
A-143, 9th Floor, Sovereign Corporate Challenge Data Science With
Legal Java Algorithms HTML
Tower, Sector-136, Noida, Uttar
Hack-A-Thon Python
Pradesh - 201305 Careers C++ DSA for Beginners CSS
GfG Weekly Data Science For
In Media PHP Basic DSA JavaScript
Contest Beginner
Contact Us Problems TypeScript
GoLang Machine Learning
Offline Classes
Advertise with us DSA Roadmap ReactJS
(Delhi/NCR) SQL Tutorial
GFG Corporate DSA Interview
DSA in JAVA/C++ R Language ML Maths NextJS
Solution Questions
Master System Android Tutorial Data Visualisation NodeJs
Placement Training Competitive
Design Tutorial
Bootstrap
Program Programming
Master CP Pandas Tutorial
Tailwind CSS
GeeksforGeeks NumPy Tutorial
Videos NLP Tutorial
Geeks Community Deep Learning
Tutorial

Python Tutorial Computer DevOps System Design School Commerce


Python Science Git High Level Design Subjects Accountancy
Programming GATE CS Notes Mathematics
AWS Low Level Design Business Studies
Examples
Operating Systems Docker UML Diagrams Physics Economics
Django Tutorial
Computer Network Kubernetes Interview Guide Chemistry Management
Python Projects
Database Azure Design Patterns Biology HR Management
Python Tkinter Management
GCP OOAD Social Science Finance
Web Scraping System
DevOps Roadmap System Design English Grammar Income Tax
OpenCV Tutorial Software
Bootcamp
Engineering
Python Interview
Interview Questions
Question Digital Logic Design

Engineering Maths

UPSC Study Preparation Competitive More Tutorials Free Online Write & Earn
Material Corner Exams Software Tools Write an Article

Polity Notes Company-Wise JEE Advanced Development Typing Test Improve an Article

Geography Notes Recruitment UGC NET Software Testing Image Editor Pick Topics to Write
Process
History Notes SSC CGL Product Code Formatters Share your
Resume Templates Management Experiences
Science and SBI PO Code Converters
Technology Notes Aptitude Project
SBI Clerk Currency Converter Internships
Preparation Management
Economy Notes
IBPS PO Random Number
Puzzles Linux
Ethics Notes Generator
IBPS Clerk
Company-Wise Excel
Previous Year Random Password
Preparation
Papers All Cheat Sheets Generator
Companies

Colleges

@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved Open In App

You might also like