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 share memory in Linux

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

Share

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

This article is about how to share memory in Linux. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

1 the concept and use process of shared memory

1) the concept of shared memory

Shared memory is one of the IPC mechanisms.

Shared memory: allows two or more processes to share a given storage area.

2) the process of using shared memory

① process 1 creates shared memory and then maps shared memory.

② process 2 acquires shared memory and maps shared memory.

③ interaction is completed, process 1 separates shared memory, process 2 separates shared memory.

④ process 1 removes shared memory.

2 shared memory related structures and functions

0) shared memory-related structures

The kernel maintains a structure for each shared segment that contains at least the following members for each shared segment.

Struct shmid_ds {struct ipc_perm shm_perm; / / size of the size_t shm_segsz; / / segment of the operation permission in bytes time_t shm_atime; / / the time the last process was attached to the segment time_t shm_dtime / / the time the last process left the segment time_t shm_ctime; / / the time the last process modified the segment pid_t shm_cpid; / / the PID pid_t shm_lpid; / / the PID shmatt_t shm_nattch of the last shmat (2) / shmdt (2) that created the segment / / the number of processes currently attached to this segment.}

The system saves an ipc_perm structure for each IPC object, which specifies the permissions and owners of the IPC object, and each version of the kernel has unused ipc_perm structure members.

Struct ipc_perm {key_t _ _ key; / / key value provided for the shmget (2) call uid_t uid; / / valid user of the shared memory owner UID gid_t gid; / / valid group GID uid_t cuid of the group to which the shared memory owner belongs / / valid user of the shared memory creator UID gid_t cgid; / / valid group ID unsigned short mode; / / privilege + SHM_DEST and SHM_LOCKED flag unsigned short _ _ seq; / / serial number} of the group to which the shared memory creator belongs

1) shmget function

The shmget function is used to create or get shared memory and return its descriptor id.

① function prototype.

Int shmget (key_t key,size_t sizie,int shmflg)

② header file.

Include include

③ parameter.

Key: the key value of shared memory.

Size: the size of shared memory.

Shmflg: open the flag that if IPC_CREAT is used, a new piece of shared memory will be created.

④ returns a value.

Success: returns the descriptor of the shared memory created or obtained.

Failed:-1.

2) shmat function

The shmat function is used to map shared memory, which connects the process to its address space.

① function prototype.

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

② header file.

Include include

③ parameter.

Shmid: the descriptor of the shared memory to map.

Shmaddr: the address of shared memory.

Shmflg: open the flag that if IPC_CREAT is used, a new piece of shared memory will be created.

④ returns a value.

Success: returns the descriptor of the shared memory created or obtained.

Failed:-1.

3) shmdt function

The shmdt function is used to separate the shared memory, that is, after the operation of the storage segment, you can use this function to disconnect the process from the storage segment, that is, to disconnect the shared memory.

① function prototype.

Int shmdt (const void * shmaddr)

② header file.

# include # include

③ parameter.

Shmaddr: the mapped address of the shared memory to be disconnected.

④ returns a value.

Success: 0.

Failed:-1.

4) shmctl function

The shmctl function is used to control shared memory, and parameters allow you to perform specific operations on shared memory.

① function prototype.

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

② header file.

# include # include

③ parameter.

Shmid: the id of the shared memory to control.

Cmd: decide what control actions to perform, such as IPC_RMID (for deletion).

Buf: gets the shmid_ds structure that describes shared memory in linux. Hardly use it.

The parameters that can be accessed by cmd are as follows. You need to refer to the above structures shmid_ds and ipc_perm:

IPC_STAT: take the shmid_ds structure of this segment and store it in the structure pointed to by the buf.

IPC_SET: set the following three fields in the shmid_ds structure associated with this shared storage segment by the values in the structure pointed to by buf: shmperm.uid, shm perm.gid, and shmperm.mode.

This command can only be executed by two processes: processes with valid user ID equal to shm_perm.cuid or shmperm.uid, and processes with superuser privileges.

IPC_RMID: removes the shared storage segment from the system.

The storage segment is not actually deleted unless the last process that uses the segment is terminated or detached from the segment.

Whether the segment is still in use or not, the segment identifier is deleted immediately, so you can no longer connect to the segment with shmat.

This command can only be executed by two processes: processes with valid user ID equal to shm_perm.cuid or shm_perm.uid, and processes with superuser privileges.

The following two commands can only be executed by the superuser:

SHM_LOCK: locks the shared storage segment in memory.

SHM_UNLOCK: unlocks the shared storage segment.

④ returns a value.

Success: different values are returned depending on the operation.

Failed:-1.

3 instance code

Here are two processes to demonstrate the use of shared memory.

The example code is as follows, which is all in the code comments.

WriteMemory.c .

# include # define SIZE 1024 / / you can enter 1K string struct SharedMemoryST {int ReadWriteFlag; / / indicate who put it in char CharData [SIZE]; / / character array saves user input data} Int main (int argc,char * argv []) {int shmid; int ReadStatusFlag = 1; / whether the data in memory is read, 1 is not read out struct SharedMemoryST * shm; / / shared memory structure variable char buffer [SIZE]; key_t key=ftok ("/ tmp", 12) / / create the key value of shared memory. If the prompt fails (usually caused by no quit), you can change the key value of the read / write process to the same number / / 1. Create shared memory shmid = shmget (key,sizeof (struct SharedMemoryST), IPC_CREAT | IPC_EXCL | 0777) If (shmid = =-1) / / if creation fails {printf ("\ nCreating share memory fail!\ n\ n"); exit (1);} / / 2 Mapping shared memory shm = shmat (shmid,NULL,0) / / memory id, location of the map, mapping flag (no special requirements) / / 3 query written while (ReadStatusFlag) / / Loop check whether the data written to the shared memory is read out, and exit the loop {while (shm- > ReadWriteFlag = = 1) {sleep (1) Printf ("\ nWaiting read memory!\ n");} / / get user input printf ("\ nPlease input data or input 'quit' to exit!\ n\ n"); fgets (buffer,SIZE,stdin) / / Parameter: the position, length and method of the string / / put the string entered by the user into the shared memory strncpy (shm- > CharData,buffer,SIZE); / / Parameter: destination data, source data, data size shm- > ReadWriteFlag = 1 If (strncmp (buffer, "quit", 4) = = 0) / / the last parameter is the number of comparison characters {ReadStatusFlag = 0; / / the data written to the shared memory has been read}} / / 4 out of the shared memory shmdt ((const void *) shm); return 0 }

ReadMemory.c .

# include # define SIZE 1024 / / you can enter a 1K string struct SharedMemoryST {int ReadWriteFlag; / / indicating whether the read process or the write process put the data char CharData [SIZE]; / / Save the user input data} Int main (int argc,char * argv []) {int shmid; int ReadStatusFlag = 1; / / the flag bit of whether the data in memory is read or not. 1 indicates that struct SharedMemoryST * shm; / / shared memory structure key_t key=ftok ("/ tmp", 12) has not been read. / / create the key value of shared memory. If prompted to fail, modify the number. Both read and write processes need to be changed to the same number / / 1. Create / get shared memory shmid = shmget (key,sizeof (struct SharedMemoryST), IPC_CREAT | 0777) / / allocation size is structure size, 1234 is random key value / / 2 Mapping shared memory shm = (struct SharedMemoryST *) shmat (shmid,NULL,0); / / memory id, location of mapping, mapping flag (no special requirements) shm- > ReadWriteFlag = 0 / / 3 check whether the message is received and receive quit exit while (ReadStatusFlag) {/ / print shared memory if (shm- > ReadWriteFlag = = 1) / equal to the corresponding data {printf ("\ nThe write context is:% s\ n", shm- > CharData); shm- > ReadWriteFlag = 0 If (strncmp (shm- > CharData, "quit", 3) = = 0) {ReadStatusFlag = 0; / / end query, exit} / / 4 detach from shared memory shmdt ((const void *) shm) / / 5 Delete shared memory shmctl (shmid,IPC_RMID,0);}

Write shared memory first create shared memory, write data, read shared memory read data, through the flag query, exit the input quit.

The running results are as follows:

Thank you for reading! This is the end of the article on "how to share memory in Linux". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!

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