Linux system Programming-interprocess communication: Shared memory

Source: Internet
Author: User

Overview

Shared memory is one of the simplest ways to communicate between processes. Shared memory consent two or many other processes to access the same piece of memory, as if the malloc () function returns a pointer to the same physical memory area to a different process.

When a process changes the contents of this address, other processes will be aware of the change.


Features of shared memory:
1) Shared memory is one of the fastest ways to share data between processes.

A process writes data to a shared memory area, and the entire process of sharing that memory area can immediately see the contents.

2) using shared memory It is important to note that the mutual exclusion of access to a given storage area between multiple processes.

If a process is writing data to a shared memory area, the other process should not read or write the data until it is done with this step.


frequently use functions

1) Create shared memory

Required header file:

#include <sys/ipc.h>

#include <sys/shm.h>


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

Function:

Create or open a piece of shared memory area.

Number of references:

key : interprocess communication key value. The return value of Ftok ().

size : The length of the shared bucket (in bytes).

SHMFLG : Identifies the behavior of the function and the permissions for shared memory. The values are as follows:

ipc_creat: Create if not present
ipc_excl: If it already exists, the return fails
bit or permission bit : You can set the access permission for shared memory after the shared memory bit or permission bit, the format and the mode_t of the Open () function (click this link for the use of open (), but the operational permissions are not used.

return value:

Success: Shared memory identifier.

Failed:-1.


The demo sample code is as follows:

#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys /types.h> #include <sys/ipc.h> #include <sys/shm.h> #define BUFSZ 1024int Main (int argc, char *argv[]) {int shmid;key_t Key;key = Ftok ("./", 2015); if (key = =-1) {perror ("Ftok");} Create shared memory Shmid = Shmget (key, BUFSZ, ipc_creat|0666), if (Shmid < 0) {perror ("Shmget"); exit ( -1);} return 0;}

the results of the execution are as follows:



2) Shared Memory mapping

Required header file:

#include <sys/types.h>

#include <sys/shm.h>


void *shmat (int shmid, const void *shmaddr, int shmflg);

Function:

put a shared memory segment is mapped to the data segment of the calling process. Simple to understand, let the process and shared memory establish a connection, let the process a pointer point to this shared memory.

Number of references:

shmid : Shared memory identifier. The return value of Shmget ().

shmaddr : The shared memory-mapped address, if NULL, is voluntarily specified by the system itself. recommended NULL .

SHMFLG : Access permissions and mapping criteria for shared memory segments (  usually 0 ), with detailed values such as the following:

0: Shared memory has read writable permissions.


shm_rdonly: Read only.


shm_rnd: (valid only if SHMADDR is not empty)

return value:

Success: Shared memory segment mapping address (equivalent to this pointer pointing to this shared memory)
Failed:-1


3) de-shared memory mapping

Required header file:

#include <sys/types.h>
#include <sys/shm.h>


int SHMDT (const void *SHMADDR);

Function:

Separates shared memory from the current process (although disconnecting does not remove shared memory.) Equivalent to having a previous pointer pointing to this shared memory, no longer pointing to).


Number of references:

shmaddr: Shared memory mapped address.

return value:

Success: 0

Failed:-1


4) Shared Memory control

Required Header files:

#include <sys/ipc.h>

#include <sys/shm.h>


int shmctl (int shmid, int cmd, struct shmid_ds *buf);

Function:

Control of shared memory properties.

Number of references:

shmid : Shared memory identifier.

cmd : Control of function functions, with values such as the following:

ipc_rmid : Delete. ( frequently use )
ipc_set : Sets the Shmid_ds parameter, which is equivalent to replacing the original attribute value of the shared memory with the attribute value in BUF.
ipc_stat : Saves the shmid_ds parameters and backs up the original attribute values from the shared memory to BUF.
shm_lock : Locks the Shared memory segment (Superuser).


shm_unlock : Unlocks the shared memory segment.


shm_lock is used to lock memory and disable memory swapping.

Does not prevent other processes from being interviewed after the shared memory is locked. The real implication is that the locked memory does not agree to be swapped into virtual memory. The advantage of this is that shared memory is kept in memory, which improves program performance.


buf: The address of the Shmid_ds data type (click this link for detailed types) to store or change the properties of the shared memory.

return value:

Success: 0

Failed:-1


examples of actual demonstrations

Let's do this for example: Create two processes, create a shared memory in a process, and write data to it. The data is read from the shared memory through the B process.


Write-side code such as the following:

#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys /types.h> #include <sys/ipc.h> #include <sys/shm.h> #define BUFSZ 512int Main (int argc, char *argv[]) {int Shmid;int ret;key_t Key;char *shmadd;//Create key value key = Ftok (".. /", 2015); if (key = =-1) {perror ("Ftok");} Create shared memory Shmid = Shmget (key, BUFSZ, ipc_creat|0666), if (Shmid < 0) {perror ("Shmget"); exit (-1);} Map Shmadd = Shmat (shmid, NULL, 0), if (Shmadd < 0) {perror ("Shmat"); _exit (-1);} Copy data to the shared memory area printf ("Copy data to shared-memory\n"); Bzero (Shmadd, BUFSZ); Shared Memory Empty strcpy (Shmadd, "How is You, mike\n"); return 0;}

read-only code such as the following:

#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys /types.h> #include <sys/ipc.h> #include <sys/shm.h> #define BUFSZ 512int Main (int argc, char *argv[]) {int Shmid;int ret;key_t Key;char *shmadd;//Create key value key = Ftok (".. /", 2015); if (key = =-1) {perror ("Ftok");} System ("ipcs-m"); View shared memory//open Shared memory Shmid = Shmget (key, BUFSZ, ipc_creat|0666), if (Shmid < 0) {perror ("Shmget"); exit (-1);}//Map Shmadd = s Hmat (Shmid, NULL, 0), if (Shmadd < 0) {perror ("Shmat"); exit (-1);} Read the shared memory area data printf ("data = [%s]\n", shmadd);//detach shared memory and current process ret = SHMDT (Shmadd), if (Ret < 0) {perror ("SHMDT"); exit (1);} else{printf ("deleted shared-memory\n");} Delete Shared memory Shmctl (Shmid, Ipc_rmid, NULL); System ("ipcs-m"); View shared memory return 0;}

the results of the execution are as follows:



This tutorial demonstrates the sample code download here.

Linux system Programming-interprocess communication: 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.