Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize shared memory in Linux

2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/01 Report--

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))

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report