A small example of MMAP () and munmap ()

Source: Internet
Author: User
MMAP () and munmap ()-Unix system functions are closer to the underlying
void* mmap(void* addr,size_t size,int prot,int flags,                       int fd, off_t offset)

The ADDR parameter can specify the first address of the ing. Generally, the value 0 is assigned to the kernel.
Size is the size of the allocated memory, in the unit of page for ing.
Prot is the permission to allocate memory. It is generally identified by prot_read | prot_write flags, which usually includes the following three:
Map_shared map_private: either. This parameter indicates whether the mapped memory is shared. map_shared is only valid for ing files.
Map_anonymous: ing physical memory, default ing file.
FD is a file descriptor, which is useful in ing files.
Offset is the file offset, which specifies the start point of the ing file.
When ing physical memory, FD and offset are given to 0.
Returns the first address. If the return value is successful, the return value is map_failed = (void *)-1.
// MMAP. C # include <stdio. h> # include <sys/Mman. h> # include <stdlib. h> # include <string. h> int main () {/* ing a piece of memory */void * P = MMAP (0, // Let the system specify the first address (virtual address) of the mapped memory 4, // map the space of 4 bytes. In fact, it will map a page of memory prot_read | prot_write, // permission. map_private | map_anonymous,/* map_anonymous: anonymous ing, when ing to memory, only anonymous ing can be used. Either map_shared or map_private is required. */0, // file descriptor, used for ing to files, 0 is ignored in memory ing); // file offset, used for files, memory ing will also ignore if (P = map_failed) {perror (" ing failed"); exit (-1) ;}int * Pi = P + 500; int I; for (I = 10; I <60; I ++) {PI [I] = I;} strcpy (p + 750, "abcdefghijklmn"); char * Pc = P; for (I = 0; I <800; I ++) {if (I % 10 = 0) printf ("\ n"); printf ("% x ", PC [I]);} printf ("P = % P \ n", P); sleep (20); munmap (p, 4 ); // while (1 );}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.