Get the App
SLTechnology News&Howtos  ›  Servers  › 

How to realize shared memory in Linux

Shulou Source: shulou.com Published: 2022-06-01 18:55:09 09月22日 Update

How to achieve shared memory in Linux, many novices are not very clear about this, in order to help you solve this problem, the following small series will explain in detail for everyone, there are people who need this to learn, I hope you can gain something.

I. Concept

Shared memory is a portion of physical memory shared by multiple processes and is the fastest way to share data between processes.

II. Realization

There are two steps:

1. Create shared memory.

2. Map shared memory.

1. Creation

The code is as follows:

int shmget(key_t key, int size, int shmflg)

When the value of key is IPC_PRIVATE, a new block of shared memory is created. shmflg is set to at least S_IRUSR| S_IWUSR Otherwise, a read/write error will occur. Success returns memory identifier, failure returns-1.

2. Mapping

The code is as follows:

int shmat(int shmid, char *shmaddr, int flag)

shmaddr is the starting address of shared memory. flag Mode of operation for memory. The usual command can be written as: shmat(shmid,NULL,0);

Success returns the start address of shared memory, failure returns-1.

III. Examples

The code is as follows:

#include

#include

#include

#include

#include

#define PERM S_IRUSR|S_IWUSR

int main(int argc ,char *argv[]){

int shmid;

pid_t pid;

if(argc!= 2){

printf("Usage: shmA [string]\n");

return -1;

}

if((shmid=shmget(IPC_PRIVATE,1024,PERM))

Tags: Memory process code success address help start fastest clear two content commands multiple internal for this data articles novices methods more Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Microsoft MariaDB Redmi vpn Shulou Tech Info