Linux Shared memory

Source: Internet
Author: User
Tags semaphore

Today Mayuyu to learn one of the important things in Linux, namely shared memory . We know that there are various IPC communication mechanisms available in Linux, such as signals, semaphores, pipelines, message queues, shared memory, and sockets. It is the most efficient to share memory. Mayuyu will use the following aspects to introduce

Contens

1. Knowledge of shared memory

2. Principle of Shared memory

3. The shared memory API in Linux

4. Read and write problems with shared memory

5. Commands for Shared memory

1. Knowledge of shared memory

Shared memory is the common use of the same piece of physical memory space between multiple processes by mapping the same piece of physical memory to a different process

of the virtual space to implement. Due to the mapping to different processes in the virtual space, different processes can be used directly, do not need to be like Message Queuing in the

Replication, so the shared memory is highly efficient.

Shared memory can be implemented by Mmap () mapping ordinary file mechanisms, or System V shared memory mechanism,System V is a

mapping files in special file system SHM enables shared memory communication between processes, meaning that each shared memory region corresponds to a special file system

A file in the SHM .

2. Principle of Shared memory

System v Shared memory places all shared data in the shared memory area, and any process that wants to access that data must be in the address space of this process

A new memory area is used to map the physical memory pages that hold the shared data. System v Shared memory obtained or created through the Shmget function

An IPC shared memory area, and returns the corresponding identifier, which the kernel guarantees shmget to acquire or create a shared memory area, initialize the share

The corresponding Shmid_kernel structure in the memory area, and also creates and opens a file of the same name in the special file system SHM, and establishes in memory

The corresponding dentry and inode structure of the file, the newly opened file does not belong to any process, all of which are system calls Shmget

function to complete.

As mentioned above, there is a control structure shmid_kernel in each shared memory area, which is a very important structure in the shared memory area.

It is a bridge between storage management and file systems, defined as follows

One of the most important domains in the struct is shm_file, which stores the address of the mapped file, each of which corresponds to a special file

A file in a system SHM, typically, a file in a special file system SHM cannot be accessed using the read (), write () method,

When the shared memory is taken to map the file to the process address space, it can be accessed using the memory access method.

For the System V shared memory area, the host of the kern_ipc_perm is the shmid_kernel structure, Shmid_kernel is used to

A shared memory area so that the kernel can control all shared areas in the system. The file type of the Shmid_kernel structure at the same time

Pointer type shm_file points to the corresponding file in the file system SHM. In this way, the shared memory area corresponds to the files in the Shm file system.

3. The shared memory API in Linux

The creation and use of shared memory under the system V IPC mechanism is done through the following four APIs.

(1) Shmget ()

Create shared memory

The function prototypes are:

This function call is used to create a new shared memory segment or to access a shared memory segment that already exists. Function call returned successfully within the share

The identifier for the save segment, or 1 if it is returned.

The parameters are described below

Key: A keyword used to represent a new or existing shared memory area.

Size: The amount of shared memory.

SHMFLG: You can specify the special identity, IPC_CREAT,IPC_EXCL, and low nine-bit permissions.

The internals of Shmget contain many important system V shared memory mechanisms that shmget when mapping shared memory areas to process space.

Does not really change the page table of the process, when the first time the process accesses the memory-mapped area, it will cause a lack of allocation of the physical page table

Page exception, and the kernel then assigns the corresponding page table to the shared memory map region based on the appropriate storage management mechanism.

(2) Shmat ()

Mapping shared memory

The function prototypes are:

After obtaining an identifier for a newly created shared memory segment or an existing shared memory segment, the shared memory segment can be called through the Shmat call

The memory space that is mapped to the process. The function call returns the address of the shared memory segment successfully, otherwise returns-1. When a shared memory segment is attached to the

After a new process, the shared counter in the Shm_array structure of the shared memory segment is incremented by 1.

Parameter description

Shmid: A keyword that shares memory.

SHMADDR: Specifies that shared memory appears at the location of the process memory address and is usually set to zero, indicating that the kernel is assigned a suitable location.

SHMFLG: Read-write properties for additional segments. A value of shm_rdonly is read-only, and the other value is read-write mode.

(3) SHMDT ()

Shared Memory de-mapping

The function prototypes are:

This function call can revoke a shared memory segment that is mapped to a process. The function call successfully returns a value of 0, otherwise returns-1. A process with a

When shared memory is detached, the shared counter value in the Shm_array structure of the shared memory segment is reduced by 1 until the counter value is 0, and the system really

Delete this shared memory page.

(4) Shmctl ()

Complete control of shared memory

The function prototypes are:

Used to query shared memory usage and perform some control operations, the function call successfully returns 0, otherwise returns-1.

Instead, the shared memory indicated by the shm_id is deleted.

The parameters are described below

Shmid: The identifier for the shared memory.

CMD: ipc_stat: Gets the state of shared memory and copies the SHMID_DS structure of shared memory into BUF.
ipc_set: Change the state of shared memory, and copy the UID, GID, mode in the SHMID_DS structure referred to by buf

Into the SHMID_DS structure of the shared memory.
ipc_rmid: Delete this piece of shared memory.

BUF: Shared memory management structure, see the shared Memory kernel structure definition section.

4. Read and write problems with shared memory

The following read-write problem is a classic instance of shared memory. Writes content to shared memory through the writer program, while the reader program writes

The shared memory data is read out, by invoking the shared memory API implementation, is also a simple practice of shared memory.

Code: Writer.cpp

#include <sys/ipc.h> #include <sys/shm.h> #include <sys/types.h> #include <unistd.h> #include <string.h> #include <stdio.h>struct person{int age;char name[25];}; void _work () {const char *file = "share"; key_t key = Ftok (file, 0); if (key = =-1) {perror ("Ftok error!"); return;} int shm_id = Shmget (key, 4096, ipc_creat); if (shm_id = =-1) {perror ("Shmget error!"); return;} Person *_map = (person*) shmat (shm_id, NULL, 0), char c = ' A ', for (int i = 0; i <; i++) {        c++;memcpy ((* (_map + i)). N Ame, &c, 1);        (* (_map + i)). Age = + i;} if (SHMDT (_map) = =-1) {perror ("Detach error!");}} int main (int argc, char **argv) {_work ();    return 0;}


Reader.cpp

#include <sys/ipc.h> #include <sys/shm.h> #include <sys/types.h> #include <string.h> #include <stdio.h>struct person{int Age;char name[25];}; void _work () {const char *file = "share"; key_t key = Ftok (file, 0); if (key = =-1) {perror ("Ftok error!"); return;} int shm_id = Shmget (key, 4096, ipc_creat); if (shm_id = =-1) {perror ("Shmget error!"); return;} Person *_map = (person*) shmat (shm_id, NULL, 0);    for (int i = 0; i < i++) {        printf ("name =%s\n", (* (_map + i)). Name);p rintf ("Age =%d\n\n", (* (_map + i)).    if (SHMDT (_map) = =-1) {perror ("Detach error!");}} int main (int argc, char **argv) {_work (); return 0;}


5. Commands for Shared memory

To talk about commands for shared memory, let's start with a command:IPCS, which is used to view the state of the current interprocess communication facility. Back with

A variety of parameters, such as Ipcs-all to see all the facilities type, mainly includes three kinds: shared memory , Message Queuing , semaphore .

Of course, you can also query the device condition of an IPC type separately.

Querying for Shared memory information

The first column is the shared memory key;

The second column is the number of shared memory shmid;

The third column is the user owner created;

The fourth column is the authority perms;

The five columns are created in size bytes;

The number of processes connected to shared memory Nattach;

The seventh column is the state status of shared memory. The display "Dest" indicates that the shared memory segment has been deleted, but there are users who are using it when

"Dest" is displayed when the Mode field of the memory is set to Shm_dest. When the user calls Shmctl's Ipc_rmid, the memory is viewed first

How many processes are associated with this memory, if the number of associations is 0, the shared memory will be destroyed, and the mode bit of the MoD that sets this memory

For Shm_dest, delete this shared memory if all processes are not used.

Querying information for Message Queuing

Querying for Semaphore information

in Linux, you can use the ipcrm command to remove flags for shared memory, semaphores, or message queues.

Recommended Documents: Http://wenku.baidu.com/link?url=LUi4JVQNPw71f_n59u40wy0gH0Yq0l0YqRhnWxpBbxFS2dI72wpg4CLkfec94Ygh_ Gugrokhcm1mf3roritvefwlfzntm0te8ssecdoa0je

Linux Shared memory

Related Article

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.