Solve Linux system v shared memory problem

  • 2021-07-03 01:14:07
  • OfStack

system v Shared Memory


#include <sys/types.h>
#include <sys/shm.h>
int shmget(key_t key, size_t size, int shmflg);

Establish: The relationship between process and shared memory

key_t key: A non-0 digit in hexadecimal.

1. There are two ways to set it.

Type 1: Call the fotk function

Chapter 2: Using IPC_PRIVATE directly

size: Size of shared memory

shmflg:

IPC_CREAT IPC_EXCL The permissions of users, group users and other users on this memory are represented by 9 bit, such as 664

Return value: Successfully returned the identification number of this shared memory; Failure returns-1 and errno is set.


#include <sys/types.h>
#include <sys/shm.h>
void *shmat(int shmid, const void *shmaddr, int shmflg);

shmid: Created by the shmget function, which is the return value of the shmget function

shmaddr:

NULL: Let the kernel request memory space

Non-NULL: Use malloc to create a space for shared memory shmid to be associated with this address. But if it is not an integer multiple of 4K, the kernel will adjust up or down.

shmflg:

SHM_RND: Read and write

SHM_RDONLY: Read-only

Return value:

Success: Return memory address

Failure: Return (void *)-1


#include <sys/types.h>
#include <sys/shm.h>
int shmdt(const void *shmaddr);

Unassociate process with shared memory

shmaddr: Return value of shmat

Return value: Success 0; Failed-1 and set errno.


#include <sys/types.h>
#include <sys/shm.h> 
int shmctl(int shmid, int cmd, struct shmid_ds *buf);

For shared memory operation, more cmd different, shared memory for different operations.

shmid: Created by the shmget function, which is the return value of the shmget function

cmd:

IPC_STAT: Get the status of shared memory

IPC_RMID: Mark deletes shared memory (deletes when the reference count of shared memory becomes 0)

IPC_SET: Set shared memory properties (modify permissions, modify shmid, and so on)

Wait

buf: shmid_ds structure

Return value: When cmd is IPC_RMID: Success 0; Failed-1 and set errno

Use the command "ipcs" to view the status of shared memory


------ Shared Memory Segments --------
key    shmid   owner   perms   bytes   nattch   status
0x00007fff 65536   ys     664    256    0
0x00007ffe 98305   ys     664    256    0
0x0000555e 131074   ys     664    256    0
0x00000011 229379   ys     664    256    3
key: First argument specified by function shmget shmid: Return value of function shmget owner: To which user created perms: Access to this shared memory bytes: Size nattch: Number of processes using this shared memory status: Shared Memory State

Summarize


Related articles: