Shared memory of Linux interprocess communication

Source: Internet
Author: User
Tags int size semaphore

Shared memory of interprocess communication

One, what is shared memory

Shared memory, as the name implies, allows two unrelated processes to access the same logical memory. Shared memory is a very efficient way to share and pass data between two running processes. Memory that is shared between different processes is usually scheduled as the same piece of physical memory. Processes can connect the same piece of shared memory to their own address space, and all processes can access the addresses in the shared memory as if they were allocated by the C-language function malloc. If a process writes data to shared memory, the changes will immediately affect any other process that can access the same piece of shared memory.

Special reminder: Shared memory does not provide a synchronization mechanism, that is, there is no automatic mechanism to prevent the second process from reading the shared memory until the first process finishes writing it. So we usually need to use other mechanisms to synchronize access to shared memory, such as semaphores.

(Signal volume reference http://11418774.blog.51cto.com/11408774/1833222).

Second, the use of shared memory

As with semaphores, a set of function interfaces is provided in Linux for use with shared memory, and interfaces with shared coexistence are very similar to semaphores and are simpler than interfaces that use semaphores. They are declared in the header file sys/shm.h.

1. Shmget function

This function is used to create shared memory, which is prototyped as:

int Shmget (key_t key, size_t size, int shmflg);

The first parameter, like the Semget function of the semaphore, requires that the program provide a parameter key (not a 0 integer), which effectively names the shared memory segment, and returns a shared memory identifier (non-negative integer) associated with the key when the Shmget function succeeds, for subsequent shared memory functions. The call failed to return-1.

Unrelated processes can access the same shared memory through the return value of the function, which represents a resource that the program may want to use, and the program accesses all shared memory indirectly, first by calling the Shmget function and providing a key. A corresponding shared memory identifier (the return value of the Shmget function) is generated by the system, and only the Shmget function uses the semaphore key directly, and all other semaphore functions use the semaphore identifier returned by the Semget function.

The second parameter, size specifies the amount of memory that needs to be shared in bytes

The third parameter, SHMFLG, is the permission flag, which functions like the mode parameter of the Open function, and can be done or manipulated with ipc_creat if it is to be created if the shared memory identified by the key does not exist. The permission flags for shared memory are the same as the read and write permissions for a file, for example, 0644, which means that shared memory that is allowed to be created by a process is read and written to shared memory by processes owned by the memory creator, while processes created by other users can read only shared memory.

2. Shmat function

it cannot be accessed by any process until the first time the shared memory is created , the Shmat function is used to initiate access to the shared memory and to connect the shared memory to the address space of the current process. Its prototype is as follows:

void *shmat (int shm_id, const void *shm_addr, int shmflg);

The first parameter, shm_id, is the shared memory identity returned by the Shmget function.

The second parameter, SHM_ADDR, specifies that the shared memory is connected to the address location in the current process, which is usually empty, indicating that the system chooses the address of the shared memory.

The third parameter, SHM_FLG, is a set of flag bits, typically 0.

When the call succeeds, returns a pointer to the first byte of shared memory if the call fails to return-1.

3. Shmdt function

This function is used to detach shared memory from the current process. Note that separating shared memory is not removing it, just making that shared memory no longer available to the current process. Its prototype is as follows:

int SHMDT (const void *SHMADDR);

The parameter shmaddr is the address pointer returned by the SHMAT function, returns 0 when the call succeeds, and returns-1 on failure.

4. Shmctl function

Like the Semctl function of semaphores, it is used to control shared memory, and its prototype is as follows:

int shmctl (int shm_id, int command, struct shmid_ds *buf);

The first argument, shm_id, is the shared memory identifier returned by the Shmget function.

The second argument, command is the action to take, it can take the following three values:

Ipc_stat: Sets the data in the SHMID_DS structure to the current associated value of shared memory, which overwrites the value of Shmid_ds with the current associated value of shared memory.

Ipc_set: If the process has sufficient permissions, set the current association value of shared memory to the value given in the SHMID_DS structure

IPC_RMID: Deleting shared memory segments

The third parameter, buf, is a struct pointer that points to the structure of shared memory mode and access permissions.

The SHMID_DS structure includes at least the following members:

struct SHMID_DS

{

uid_t Shm_perm.uid;

uid_t Shm_perm.gid;

mode_t Shm_perm.mode;

};

As an example,

Create a shared memory, two processes one read, one write, no synchronization mechanism, the write process writes a ' a ' to memory every 1 seconds, and the read process reads the data in shared memory every 1 seconds and prints it out.

Project documents:

Comm.h: The function declaration required for encapsulation

COMM.C: Implementation of functions

SEVER.C: Service side (read process)

CLIENT.C: Client (write process)

Comm.h

#pragma once#include <stdio.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/shm.h > #include <errno.h> #define _PROJ_NAME_ "./tmp" #define _PROJ_ID_ 0x6666int create_shm (int size); int Get_shm (); int destory_shm (int shm_id); void* Attach (int shm_id); int detach (void* addr);

Comm.c

#include   "comm.h" Static int comm_shm (int size, int flag) {     key_t _key = ftok (_proj_name_, _proj_id_);     if (_key <  0)     {        perror ("Ftok");         return -1;    }    int  Shm_id = shmget (_key, size, flag);     if (shm_id < 0)     {        perror ("Shmget");         return -2;    }    return shm_ ID;} INT&NBSP;CREATE_SHM (int size) {&NBSP;&NBSP;&NBSP;&NBSP;INT&NBSP;FLAG&NBSP;=&NBSP;IPC_CREAT&NBSP;|&NBSP;IPC _EXCL&NBSP;|&NBSP;0644;&NBSP;&NBSP;&NBSP;&NBSP;RETURN&NBSP;COMM_SHM (Size, flag);} Int get_shm () {    int&NBSP;FLAG&NBSP;=&NBSP;IPC_CREAT;&NBSP;&NBSP;&NBSP;&NBSP;RETURN&NBSP;COMM_SHM (0, flag);} INT&NBSP;DESTORY_SHM (int shm_id) {    int ret = shmctl (Shm_id, IPC _rmid, null);     if (ret < 0)     {         perror ("Shmctl");        return -1;     }    return 0;} Void* attach (int shm_id) {    return shmat (shm_id, null, 0);} Int detach (void* addr) {    return shmdt (addr);}

Sever.c

Sever.c#include "comm.h" int main () {int shm_id = CREATE_SHM (4097);    void* addr = Attach (shm_id);        while (1) {printf ("%s\n", (char*) addr);    Sleep (1);    } detach (addr);    DESTORY_SHM (shm_id); return 0;}

Client.c

Client.c#include "comm.h" int main () {int shm_id = GET_SHM ();    char* addr = (char*) attach (shm_id);    int index = 0;        while (1) {addr[index++] = ' A ';        Addr[index] = ' + ';    Sleep (1);    } detach (addr); return 0;}

Run results

650) this.width=650; "src=" Http://s4.51cto.com/wyfs02/M01/85/4D/wKiom1efY-OhT2FfAAA8T1Xuqz8156.png "title=" 3.png " alt= "Wkiom1efy-oht2ffaaa8t1xuqz8156.png"/>

650) this.width=650; "src=" Http://img.baidu.com/hi/jx2/j_0023.gif "alt=" J_0023.gif "/>650) this.width=650; "src=" Http://img.baidu.com/hi/jx2/j_0023.gif "alt=" j_0023.gif "/>650) this.width=650; "src=" Http://img.baidu.com/hi/jx2/j_0023.gif "alt=" j_0023.gif "/>650) this.width=650; "src=" Http://img.baidu.com/hi/jx2/j_0023.gif "alt=" j_0023.gif "/>650) this.width=650; "src=" Http://img.baidu.com/hi/jx2/j_0023.gif "alt=" j_0023.gif "/>650) this.width=650; "src=" Http://img.baidu.com/hi/jx2/j_0023.gif "alt=" j_0023.gif "/>650) this.width=650; "src=" Http://img.baidu.com/hi/jx2/j_0023.gif "alt=" j_0023.gif "/>650) this.width=650; "src=" Http://img.baidu.com/hi/jx2/j_0023.gif "alt=" j_0023.gif "/>650) this.width=650; "src=" Http://img.baidu.com/hi/jx2/j_0023.gif "alt=" j_0023.gif "/>650) this.width=650; "src=" Http://img.baidu.com/hi/jx2/j_0023.gif "alt=" j_0023.gif "/>650) this.width=650; "src=" Http://img.baidu.com/hi/jx2/j_0023.gif "alt=" j_0023.gif "/>650) this.width=650; "src=" Http://img.baidu.com/hi/jx2/j_0023.gif "alt=" j_0023.gif "/>650) this.width=650; "src=" Http://img.baidu.com/hi/jx2/j_0023.gif "alt=" j_0023.gif "/>

This article is from the "11408774" blog, please be sure to keep this source http://11418774.blog.51cto.com/11408774/1833276

Shared memory of Linux interprocess communication

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.