About Linux IPC (iii): MMAP system calls shared memory

Source: Internet
Author: User
Tags function prototype

"Copyright Notice: respect for the original, reproduced please retain the source: blog.csdn.net/shallnet or .../gentleliu, the article is for learning communication only, do not use for commercial purposes"
Before the process of communication between the sockets, this way to pass data between processes first need to copy the data from the process 1 address space to the kernel, the kernel then copy the data into the address space of process 2, that is, data passing through the kernel pass. This is not very efficient when processing more data, and allowing multiple processes to share a memory area solves the problem of previous socket process communication. Shared memory is the fastest inter-process communication, where a piece of memory is mapped into multiple process address spaces, and data transfer between processes is not involved in the kernel.
Shared memory is not separated from the memory that a process has, and the memory of the process is always private. Shared memory is allocated from the system's free memory pool, and each process that wants to access it connects to it. This connection process is called mapping, which assigns the shared memory segment a local address in the address space of each process.
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 same file as the normal memory without having to call read (), write (), and so on. The function prototypes are:
     #include <sys/mman.h>     void *mmap (void *addr, size_t length, int prot, int flags,  
Where the parameter addr is the descriptor FD should be mapped to the start address of the process space, when NULL is specified, the kernel will itself choose the starting address, regardless of whether addr is null, the function return value is the starting address of the memory that FD maps to;
Len is the number of bytes mapped to the calling process address space, starting with offset bytes at the beginning of the mapped file, and offset is usually set to 0;
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), the value is often set to Prot_read | Prot_write.
Flags are specified by the following constant values: map_shared, Map_private, map_fixed, where map_shared (changes are shared, all processes are visible to the modified shared memory), Map_private (the change is private, Only visible to the process for shared memory modification is required, and map_fixed is not recommended for use.

MUNMP () deletes the address mapping relationship, the function prototype is as follows:
     #include <sys/mman.h>       int munmap (void *addr, size_t length);
The parameter addr is the address returned by Mmap, and Len is the size of the map area.

The changes to the shared content of the process in the mapping space are not directly written back to the disk file, and are often performed after calling Munmap (). You can implement the content of the file on disk by calling Msync () to match the contents of the shared memory area. The Msync () function prototype is:
       #include <sys/mman.h>       int msync (void *addr, size_t length, int flags);
The parameters addr and Len represent the memory area, flags have the following values specified, Ms_async (performs asynchronous write), Ms_sync (performs synchronous write), ms_invalidate (invalidates cache). where Ms_async and Ms_sync two values must and can only specify one, once the write operation into the kernel, Ms_async immediately return, Ms_sync to wait until the completion of the write operation is not returned. If Ms_invalidate is also specified, all in-memory copies of file data that are inconsistent with their final copy are invalidated.

After opening a file with the Open function, call mmap to map the contents of the file to the address space of the calling process, so that we manipulate the file content only to operate on the mapped address space, without having to use functions such as open,write.

The steps to using shared memory are basically:
Open () to create a memory segment;
Use Ftruncate () to set its size;
Use Mmap () to map it to process memory and perform the actions required by other participants;
When it is finished, the original process calls Munmap () and exits.
Here's a look at the implementation:
The server program creates memory and writes data to shared memory:
int Sln_shm_get (char *shm_file, void **shm, int mem_len) {    int fd;    FD = open (Shm_file, O_RDWR | O_creat, 0644);//1. Create a memory segment    if (FD < 0) {        printf ("Open <%s> failed:%s\n", Shm_file, Strerror (errno));        return-1;    }    Ftruncate (FD, Mem_len);//2. Set shared memory size    *SHM = mmap (NULL, Mem_len, Prot_read | Prot_write, map_shared, FD, 0); Mmap Mapping system memory pool to process memory    if (map_failed = = *shm) {        printf ("Mmap:%s\n", Strerror (errno));        return-1;    }    Close (FD);    return 0;} int main (int argc, const char *argv[]) {    char *shm_buf = NULL;    Sln_shm_get (Shm_ipc_filename, (void * *) &shm_buf, shm_ipc_max_len);    snprintf (Shm_buf, Shm_ipc_max_len, "Hello Share memory ipc! I ' m server. ");    return 0;}
The client program maps the shared memory and reads the data:
int main (int argc, const char *argv[]) {    char *shm_buf = NULL;    Sln_shm_get (Shm_ipc_filename, (void * *) &shm_buf, shm_ipc_max_len);    printf ("IPC Client get:%s\n", shm_buf);    Munmap (Shm_buf, Shm_ipc_max_len);    return 0;}
Execute the server program to write the data to the shared memory before running the client program, the result is as follows:
#./server#./CLIENTIPC client Get:hello share memory ipc! I ' M server.#
Shared memory does not have the same synchronization mechanism as the socket itself, it needs to be synchronized by adding additional synchronization operations, such as semaphores. Synchronization-related operations are described in detail later in the relevant column.

Download the source code in this section:

http://download.csdn.net/detail/gentleliu/8140487

Finally, I wish you a Happy Single Program APE FESTIVAL!!!!!


About Linux IPC (iii): MMAP system calls shared memory

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.