Shared Memory Mmap Learning and the difference from SHMXXX operations

Source: Internet
Author: User

The previous article learned about shared memory: http://www.cnblogs.com/charlesblc/p/6142139.html

According to this http://blog.chinaunix.net/uid-26335251-id-3493125.html

One more article:

1. Shared memory allows two or more processes to share a given store, because the data does not need to replicate back and forth, so it is the fastest inter-process communication mechanism. Shared memory can be implemented through the mmap () mapping of ordinary files (in special cases, anonymous mappings), or through the System V shared memory mechanism.

The application interface and principle are simple and the internal mechanism is complex. In order to achieve more secure communication, it is often used in conjunction with synchronization mechanisms such as semaphores.

The mechanism of MMAP is to create a file on disk, each in the process memory, to open a separate space for mapping. If the process is multiple, then the actual physical memory (main memory) is not consumed too much.

SHM mechanism: The shared memory of each process is mapped directly into the actual memory.

Conclusion:

1, Mmap saved to the actual hard disk, the actual storage is not reflected in main memory. Advantage: Storage can be very large (more than main memory); disadvantage: Process reads and writes are slower than memory.

2, SHM saved to physical memory (main memory), the actual storage capacity directly reflected in main memory. Advantages, inter-process access speed (read-write) faster than disk, disadvantage, storage capacity is not very large (more than main memory)

Use SHM: If the amount of storage allocated is not large, then use the SHM.

Mmap is a file operation.

The MMAP function is a system call under Unix/linux, which is described in detail in section 12.2 of the Unix Netword programming volume.

Mmap system calls are not designed entirely for shared memory. It itself provides a different way of accessing ordinary files than normal, and processes can operate on ordinary files like read-write memory. The shared memory IPC for POSIX or System V is purely for sharing purposes, and of course mmap () realizes shared memory is also one of its main applications.
Mmap system calls enable shared memory between processes by mapping the same common file. After the normal file is mapped to the process address space, the process can access the file like normal memory without having to call read (), write (), and so on. Mmap does not allocate space, it simply maps the file to the address space of the calling process, and then you can write the file with memcpy and so on, instead of writing (). After writing, use Msync () to sync, and the content you write is saved to the file. However, there is no way to increase the length of the file because the length of the map is determined when the mmap () is called.

Simply put the contents of a file in memory to make an image, memory faster than the disk.
Basically it's a file that corresponds to a section of your virtual memory and returns a pointer.

The system calls mmap () to share memory in two ways :
(1) Memory mapping provided with normal files: applies to any process; At this point, you need to open or create a file and then call Mmap (); The typical calling code is as follows:
Fd=open (name, flag, mode);
if (fd<0)
...
Ptr=mmap (NULL, Len, prot_read| Prot_write, map_shared, FD, 0); There are many features and areas to be aware of in the way that shared memory is communicated through MMAP (), which we will specify in the example.
(2) Use special files to provide anonymous memory mapping: Applies to relationships between processes; Because of the special affinity of a parent-child process, call Mmap () first in the parent process and then call Fork (). Then, after calling Fork (), the child process inherits the address space of the parent process after the anonymous mapping and also inherits the address returned by Mmap (), so that the parent-child process can communicate through the mapped area. Note that this is not a general inheritance relationship. In general, child processes maintain separate variables inherited from the parent process. The address returned by the mmap () is maintained by the parent-child process together.

1, mmap () system call form as follows:

void* mmap (void * addr, size_t len, int prot, int flags, int fd, off_t offset)
The parameter fd is the file descriptor that will be mapped to the process space, usually returned by open (), and the FD can be specified as-1, at which point the Map_anon in the flags parameter must be specified, indicating that the anonymous mapping is performed (no specific file names are involved, and file creation and opening are avoided , it is obvious that it can only be used for inter-process communication with affinity. Len is the number of bytes mapped to the calling process address space, starting at offset bytes at the beginning of the mapped file. The prot parameter specifies the access rights for shared memory. The following values may be desirable or: prot_read (readable), prot_write (writable), prot_exec (executable), Prot_none (inaccessible). Flags are specified by the following constant values: map_shared, Map_private, map_fixed, where map_shared, map_private is required, and map_fixed is not recommended. The offset parameter is typically set to 0, which indicates that the mapping starts from the file header. The addr parameter specifies that the file should be mapped to the start address of the process space and is typically assigned a null pointer, at which point the task of selecting the start address is left to the kernel. The return value of the function is the address that the last file maps to the process space, and the process can manipulate the starting address directly to the valid address of the value. The parameters of mmap () are no longer detailed here, and readers can refer to the mmap () manual page for further information.

Iii. examples of mmap ()

Here are two examples of using mmap (): Example 1 gives two processes for shared memory communication by mapping ordinary files, and Example 2 gives the parent-child process the shared memory through anonymous mapping. The system calls Mmap () There are many interesting places, below is through mmap () mapping ordinary files to implement the process of communication between the example, we use this example to illustrate the mmap () implementation of shared memory features and considerations.

Example 1: Two processes for shared memory communication by mapping plain files

/*-------------map_normalfile1.c-----------*/#include<sys/mman.h>#include<sys/types.h>#include<fcntl.h>#include<unistd.h>typedefstruct{    Charname[4]; intAge ;} People;main (intargcChar* * argv)//Map a normal file as shared mem:{    intFd,i; People*P_map; Chartemp; FD=open (argv[1],o_creat| o_rdwr| O_trunc,00777); Lseek (FD,sizeof(People) *5-1, Seek_set); Write (FD,"",1); P_map= (people*) mmap (NULL,sizeof(People) *Ten, prot_read| PROT_WRITE,MAP_SHARED,FD,0 );    Close (FD); Temp='a';  for(i=0; i<Ten; i++) {Temp+=1; memcpy ((* (P_map+i)). Name, &temp,2 ); ( * (P_map+i)). Age = -+i; } printf ("initialize over \ n"); Sleep (Ten); Munmap (P_map,sizeof(People) *Ten ); printf ("Umap OK \ n" );}/*-------------map_normalfile2.c-----------*/#include<sys/mman.h>#include<sys/types.h>#include<fcntl.h>#include<unistd.h>typedefstruct{    Charname[4]; intAge ;} People;main (intargcChar* * argv)//Map a normal file as shared mem:{    intFd,i; People*P_map; FD=open (argv[1],o_creat| O_RDWR,00777 ); P_map= (people*) mmap (NULL,sizeof(People) *Ten, prot_read| PROT_WRITE,MAP_SHARED,FD,0);  for(i =0;i<Ten; i++) {printf ("Name:%s Age%d;\n", (* (P_map+i)). Name, (* (p_map+i)).    Age); } munmap (P_map,sizeof(People) *Ten );}

Example 2: The parent-child process implements shared memory through anonymous mappings

#include <sys/mman.h>#include<sys/types.h>#include<fcntl.h>#include<unistd.h>typedefstruct{    Charname[4]; intAge ;} People;main (intargcChar**argv) {    inti; People*P_map; Chartemp; P_map= (people*) mmap (NULL,sizeof(People) *Ten, prot_read| prot_write,map_shared| map_anonymous,-1,0); if(fork () = =0) {Sleep (2);  for(i =0;i<5; i++) printf ("Child read:the%d People 's is%d\n", i+1, (* (p_map+i)).        Age); (*P_MAP). Age = -; Munmap (P_map,sizeof(People) *Ten);//in fact, when the process terminates, the mapping is automatically de-mapped. exit (); } temp='a';  for(i =0;i<5; i++) {Temp+=1; memcpy ((* (P_map+i)). Name, &temp,2); (* (P_map+i)). age= -+i; } Sleep (5); printf ("parent Read:the First People,s age is%d\n",(*p_map). Age); printf ("umap\n"); Munmap (P_map,sizeof(People) *Ten ); printf ("Umap ok\n" );}

Shared memory Mmap learning and differences from SHMXXX operations

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.