Mmap

In computing, mmap(2) is a POSIX-compliant Unix system call that maps files or devices into memory. It is a method of memory-mapped file I/O. It implements demand paging because file contents are not immediately read from disk and initially use no physical RAM at all. The actual reads from disk are performed after a specific location is accessed, in a lazy manner. After the mapping is no longer needed, the pointers must be unmapped with munmap(2). Protection information—for example, marking mapped regions as executable—can be managed using mprotect(2), and special treatment can be enforced using madvise(2).

In Linux, macOS and the BSDs, mmap can create several types of mappings. Other operating systems may only support a subset of these; for example, shared mappings may not be practical in an operating system without a global VFS or I/O cache.

History

The original design of memory-mapped files came from the TOPS-20 operating system. mmap and associated systems calls were designed as part of the Berkeley Software Distribution (BSD) version of Unix. Their API was already described in the 4.2BSD System Manual, even though it was neither implemented in that release, nor in 4.3BSD.[1] Sun Microsystems had implemented this very API, though, in their SunOS operating system. The BSD developers at University of California, Berkeley unsuccessfully requested Sun to donate its implementation; 4.3BSD-Reno was instead shipped with an implementation based on the virtual memory system of Mach.[2]

File-backed and anonymous

File-backed mapping maps an area of the process's virtual memory to files; that is, reading those areas of memory causes the file to be read. It is the default mapping type.

Anonymous mapping maps an area of the process's virtual memory not backed by any file, made available via the MAP_ANONYMOUS/MAP_ANON flags. The contents are initialized to zero.[3] In this respect an anonymous mapping is similar to malloc, and is used in some malloc implementations for certain allocations, particularly large ones.

Memory visibility

If the mapping is shared (the MAP_SHARED flag is set), then it is preserved when a process is forked (using a fork(2) system call). Therefore, writes to a mapped area in one process are immediately visible in all related (parent, child or sibling) processes. If the mapping is shared and backed by a file (not MAP_ANONYMOUS) the underlying file medium is only guaranteed to be written after it is passed to the msync(2) system call. In contrast, if the mapping is private (the MAP_PRIVATE flag is set), the changes will neither be seen by other processes nor written to the file.

A process reading from, or writing to, the underlying file will not always see the same data as a different process that has mapped the file, since segments of the file are copied into RAM and only periodically flushed to disk. Synchronization can be forced with a call to msync(2).

Using mmap on files can significantly reduce memory overhead for applications accessing the same file; they can share the memory area the file encompasses, instead of loading the file for each application that wants access to it. This means that mmap(2) is sometimes used for Interprocess Communication (IPC). On modern operating systems, mmap(2) is typically preferred to the System V IPC Shared Memory facility.[4]

The main difference between System V shared memory (shmem) and memory mapped I/O (mmap) is that System V shared memory is persistent: unless explicitly removed by a process, it is kept in memory and remains available until the system is shut down. mmap'd memory is not persistent between application executions (unless it is backed by a file).

Example of usage under the C programming language

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

/* This example shows how an mmap of /dev/zero is equivalent to
   using anonymous memory (MAP_ANON) not connected to any file.
   N.B. MAP_ANONYMOUS or MAP_ANON are supported by most UNIX
   versions, removing the original purpose of /dev/zero.
*/
/* Does not work on OS X or macOS, where you can't mmap over /dev/zero */
int main(void)
{
        const char str1[] = "string 1";
        const char str2[] = "string 2";
        pid_t parpid = getpid(), childpid;
        int fd = -1;
        char *anon, *zero;

        if ((fd = open("/dev/zero", O_RDWR, 0)) == -1)
                err(1, "open");

        anon = (char*)mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_ANON|MAP_SHARED, -1, 0);
        zero = (char*)mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);

        if (anon == MAP_FAILED || zero == MAP_FAILED)
                errx(1, "either mmap");

        strcpy(anon, str1);
        strcpy(zero, str1);

        printf("PID %d:\tanonymous %s, zero-backed %s\n", parpid, anon, zero);
        switch ((childpid = fork())) {
        case -1:
                err(1, "fork");
                /* NOTREACHED */
        case 0:
                childpid = getpid();
                printf("PID %d:\tanonymous %s, zero-backed %s\n", childpid, anon, zero);
                sleep(3);

                printf("PID %d:\tanonymous %s, zero-backed %s\n", childpid, anon, zero);
                munmap(anon, 4096);
                munmap(zero, 4096);
                close(fd);
                return EXIT_SUCCESS;
        }

        sleep(2);
        strcpy(anon, str2);
        strcpy(zero, str2);

        printf("PID %d:\tanonymous %s, zero-backed %s\n", parpid, anon, zero);
        munmap(anon, 4096);
        munmap(zero, 4096);
        close(fd);
        return EXIT_SUCCESS;
}

sample output:

PID 22475:      anonymous string 1, zero-backed string 1
PID 22476:      anonymous string 1, zero-backed string 1
PID 22475:      anonymous string 2, zero-backed string 2
PID 22476:      anonymous string 2, zero-backed string 2

Usage in database implementations

The mmap system call has been used in various database implementations as an alternative for implementing a buffer pool, although this created a different set of problems that could realistically only be fixed using a buffer pool.[5]

See also

  • Virtual memory for when there is more address space than physical memory
  • Paging for the implementation of virtual memory
  • Page cache for a disk caching mechanism utilized by mmap
  • Demand paging for a scheme implemented by mmap

References

  1. ^ William Joy; Eric Cooper; Robert Fabry; Samuel Leffler; Kirk McKusick; David Mosher (1983). 4.2BSD System Manual (PDF) (Report). Computer Systems Research Group, University of California, Berkeley.
  2. ^ McKusick, Marshall Kirk (1999). "Twenty Years of Berkeley Unix: From AT&T-Owned to Freely Redistributable". Open Sources: Voices from the Open Source Revolution. O'Reilly.
  3. ^ "mmap(2) - The Open Group Base Specifications Issue 8".
  4. ^ Kerrisk, Michael (2010). The Linux programming interface : a Linux and UNIX system programming handbook. San Francisco: No Starch Press. p. 1116. ISBN 978-1-59327-291-3. OCLC 728672600.
  5. ^ "Are You Sure You Want to Use MMAP in Your Database Management System?". db.cs.cmu.edu. Retrieved 2023-07-04.

Further reading

Read other articles:

Pour les articles homonymes, voir Appia. Adolphe AppiaAdolphe AppiaBiographieNaissance 1er septembre 1862GenèveDécès 29 février 1928 (à 65 ans)NyonNationalité suisseActivité architecte, scénographePère Louis AppiaAutres informationsArchives conservées par Fondation SAPA, Archives suisses des arts de la scène[1]modifier - modifier le code - modifier Wikidata Adolphe Appia (né à Genève le 1er septembre 1862 et mort à Nyon le 29 février 1928) est un décorateur et metteur e...

 

 

SantanDaerahKawasan tropisBahan utamaKelapaSunting kotak info • L • BBantuan penggunaan templat ini Buku resep: Santan  Media: Santan Santan adalah cairan berwarna putih susu yang berasal dari parutan daging kelapa tua yang dibasahi sebelum akhirnya diperas dan disaring.[1][2] Wujudnya yang tidak tembus cahaya dan rasanya yang kaya disebabkan oleh kandungan minyak, bagian terbesarnya adalah lemak jenuh. Santan kelapa adalah bahan makanan yang merakyat di...

 

 

Ekolog NMFS SE Panama City Laboratory mengambil sampel darah hiu di Teluk Meksiko. National Marine Fisheries Service (NMFS) adalah badan federal Amerika Serikat yang bertugas menataguna dan memanajemen sumber daya laut hidup dan habitatnya di Zona Ekonomi Eksklusif Amerika Serikat, yang membentang 200 mil laut dari garis pantai (sekitar 370 kilometer). Dengan menggunakan alat yang disediakan oleh Magnuson-Stevens Fishery Conservation and Management Act, NMFS menilai dan memprediksi status per...

Jacques de Molay Mahaguru Kesatria Kenisah ke-23Masa jabatan1292–1312Penguasa monarki Philippe IV PendahuluThibaud GaudinPenggantiTarekat Dibubarkan Informasi pribadiLahirkira-kira 1240–1250[1]Molay, Haute-Saône, Kadipaten BourgogneMeninggal11 atau 18 Maret 1314 (usia kira-kira 70)[2]Paris, PrancisKarier militerPihakKesatria KenisahMasa dinas1265–1314Pangkat MahaguruSunting kotak info • L • B Jacques de Molay adalah mahaguru (Grand Master) Kesatria Ke...

 

 

951 Gaspra, adalah salah sebuah Benda Kecil Tata Surya dalam sabuk asteroid, berukuran panjang sekitar 18 km (foto oleh Wahana Galileo). Benda Kecil Tata Surya (bahasa Inggris: Small Solar System Body) adalah istilah yang didefinisikan pada 2006 oleh Persatuan Astronomi Internasional untuk menyebut benda-benda dalam Tata Surya yang bukan planet atau planet katai: Semua benda lain yang mengorbit Matahari akan dirujuk secara bersama-sama sebagai Benda Kecil Tata Surya ... Benda-benda tersebut s...

 

 

Dedy Wahyudi Wakil Wali Kota Bengkulu ke-2PetahanaMulai menjabat 24 September 2018PresidenJoko WidodoGubernurRidwan MuktiRohidin MersyahWali KotaHelmi Hasan PendahuluPatriana SosialindaPenggantiPetahana Informasi pribadiLahir7 Desember 1975 (umur 48)IndonesiaKebangsaanIndonesiaPartai politikPANSuami/istriDian Fitriani, SESunting kotak info • L • B Dr. Dedy Wahyudi, S.E., M.M.[1] (lahir 7 Desember 1975) adalah Wakil Wali Kota Bengkulu periode 2018–2023. Ia ...

Fashion school of the State University of New York Fashion Institute of TechnologyTypePublic collegeEstablished1944; 80 years ago (1944)Parent institutionState University of New YorkPresidentJoyce F. BrownStudents8,767[1]Undergraduates8,555Postgraduates212LocationNew York City, United States40°44′48″N 73°59′39″W / 40.74667°N 73.99417°W / 40.74667; -73.99417CampusUrban, 1.5 blocksNicknameTigersMascotStitchWebsitewww.fitnyc.edu The F...

 

 

Voivodeship of Poland Voivodeship in PolandOpole Voivodeship Województwo opolskieVoivodeship FlagCoat of armsBrandmarkLocation within PolandAdministrative divisionsCoordinates (Opole): 50°40′N 17°56′E / 50.667°N 17.933°E / 50.667; 17.933Country PolandCapitalOpoleCounties 1 city, 11 land counties,further divided into 71 gminas OpoleBrzeg CountyGłubczyce CountyKędzierzyn-Koźle CountyKluczbork CountyKrapkowice CountyNamysłów CountyNysa CountyOlesno ...

 

 

Public park in New York City Spring Creek ParkTypePublic parkLocationSpring Creek, Brooklyn and Howard Beach, Queens, New YorkCoordinates40°39′03″N 73°50′56″W / 40.650890°N 73.848957°W / 40.650890; -73.848957Operated byNew York City Department of Parks and Recreation, National Park Service Spring Creek Park is a public park along the Jamaica Bay shoreline between the neighborhoods of Howard Beach, Queens, and Spring Creek, Brooklyn, in New York City. C...

土库曼斯坦总统土库曼斯坦国徽土库曼斯坦总统旗現任谢尔达尔·别尔德穆哈梅多夫自2022年3月19日官邸阿什哈巴德总统府(Oguzkhan Presidential Palace)機關所在地阿什哈巴德任命者直接选举任期7年,可连选连任首任萨帕尔穆拉特·尼亚佐夫设立1991年10月27日 土库曼斯坦土库曼斯坦政府与政治 国家政府 土库曼斯坦宪法 国旗 国徽 国歌 立法機關(英语:National Council of Turkmenistan) ...

 

 

W59

American thermonuclear missile warhead For other uses, see W59 (disambiguation). W59 The Mark 5 Reentry Vehicle[a] that housed the W59 warheadTypeNuclear warheadService historyIn service1962 to 1969Used byUnited StatesProduction historyDesignerLos Alamos National LaboratorySpecificationsMass550 pounds (250 kg)Length47.8 inches (121 cm)Width16.3 inches (41 cm)DetonationmechanismContact, airburstBlast yield800 kilotonnes of TNT (3,300 TJ) The W59 was a...

 

 

Piala Dunia Wanita FIFA 1995(Swedia) Världsmästerskapet i fotboll för damer 1995Informasi turnamenTuan rumah SwediaJadwalpenyelenggaraan5–18 Juni 1995Jumlahtim peserta12 (dari 6 konfederasi)Tempatpenyelenggaraan5 (di 5 kota)Hasil turnamenJuara Norwegia (gelar ke-1)Tempat kedua JermanTempat ketiga Amerika SerikatTempat keempat TiongkokStatistik turnamenJumlahpertandingan26Jumlah gol99 (3,81 per pertandingan)Jumlahpenonton112.213 (4.316 per pert...

Municipal building in Kendal, Cumbria, England Kendal Town HallLocationKendal, CumbriaCoordinates54°19′37″N 2°44′50″W / 54.3269°N 2.7471°W / 54.3269; -2.7471Built1827ArchitectFrancis Webster Listed Building – Grade IIDesignated24 April 1951Reference no.1318980 Location of Kendal Town Hall in Cumbria The Town Hall is a municipal building in Highgate, Kendal, Cumbria. It is a Grade II listed building. It serves as the headquarters of Kendal Town Counci...

 

 

State government official, typically second highest officer after the governor Method for electing the lieutenant governor.   Same ticket   Same ticket in the general election, separate election in the primaries   Separate election   Title given to leader of state senate   Position nonexistent This article is part of a series on theState governments of the United States State constitution Comparison Statehouse Executive State executives Govern...

 

 

  فيشهورود (بالأوكرانية: Вишгород)‏  فيشهورود فيشهورود تقسيم إداري البلد أوكرانيا  [1] خصائص جغرافية إحداثيات 50°35′00″N 30°29′07″E / 50.583277777778°N 30.485333333333°E / 50.583277777778; 30.485333333333   المساحة 11.4 كيلومتر مربع  الارتفاع 112 متر  السكان التعداد السكاني 29913 (1 �...

كانغانا رانوت (بالإنجليزية: Kangana Ranaut)‏    معلومات شخصية الميلاد 23 مارس 1987 (37 سنة)[1]  مقاطعة مندي[2]  الإقامة هِماجل بَردِيش  مواطنة الهند  الديانة هندوسية[3]  الحياة العملية المدرسة الأم أكاديمية نيويورك للأفلام  المهنة ممثلة  اللغات الهندي�...

 

 

Diocese of the Church of England Diocese of DerbyDioecesis DerbiensisThe nave of Derby CathedralCoat of armsFlagLocationEcclesiastical provinceCanterburyArchdeaconriesDerbyshire Peak and Dales, Derby City and South Derbyshire, East DerbyshireStatisticsParishes255[1]Churches332InformationCathedralDerby CathedralCurrent leadershipBishopLibby Lane, Bishop of DerbySuffraganMalcolm Macnaughton, Bishop of ReptonArchdeaconsMatthew Trick, Archdeacon of Derby City and South Derbyshir...

 

 

Genus of spiders Plebs P. eburnus on web. Scientific classification Domain: Eukaryota Kingdom: Animalia Phylum: Arthropoda Subphylum: Chelicerata Class: Arachnida Order: Araneae Infraorder: Araneomorphae Family: Araneidae Genus: PlebsJoseph & Framenau, 2012[1] Type species P. eburnus(Keyserling, 1886) Species 22, see text Plebs bradleyi Plebs is a genus of orb-weaver spiders first described by M. M. Joseph & V. W. Framenau in 2012.[2] Though many of its species have be...

الندى معلومات عامة النوع إسلامية تاريخ التأسيس أبريل 2013 البلد  مصر المقر الرسمي القاهرة الموقع الرسمي موقع قناة الندى عبر الساتل نايل سات تعديل مصدري - تعديل   قناة الندى هي قناة فضائية إسلامية تسعى لتقديم خدمة إعلامية متميزة في مختلف مجالات الحياة في إطار ثوبٍ إسلام�...

 

 

العلاقات التشيلية الجورجية تشيلي جورجيا   تشيلي   جورجيا تعديل مصدري - تعديل   العلاقات التشيلية الجورجية هي العلاقات الثنائية التي تجمع بين تشيلي وجورجيا.[1][2][3][4][5] مقارنة بين البلدين هذه مقارنة عامة ومرجعية للدولتين: وجه المقارنة تشيلي ج...