Linux shared memory details

  
 


Linux shared memory

Shared memory is a memory area reserved by the system for communication between multiple processes. In the /proc/sys/kernel/directory, some restrictions on shared memory are recorded, such as the maximum number of bytes in a shared memory area, shmmax, the maximum number of shared memory area identifiers in the system, shmmni, etc., which can be adjusted manually. But this is not recommended.

1. Application

The use of shared memory mainly includes the following APIs: ftok(), shmget(), shmat(), shmdt(), and shmctl().

1) Use the ftok() function to get an ID number.

Application Note:

In IPC, we often use the value of key_t to create or open a semaphore. , shared memory and message queues.

Function prototype:
key_t ftok(const char *pathname, int proj_id);

Keys:

1)pathname must exist in the system and the process can access < Br>

2)proj_id is an integer value between 1 and 255. A typical value is an ASCII value.

When successful execution, a key_t value will be returned, otherwise -1 is returned. We can use strerror(errno) to determine the specific error message.

Considering that the application system may be applied on different hosts, you can directly define a key instead of ftok:
#define IPCKEY 0x344378

2)shmget() is used to open/point a piece Shared Memory Function

Application Description:

shmget() is used to obtain the ID of the shared memory area. If the specified shared area does not exist, the corresponding area is created.

Function prototype:
int shmget(key_t key, size_t size, int shmflg);

key_t key is the identifier of this shared memory. If it is an interprocess communication of a parent-child relationship, this identifier is replaced with IPC_PRIVATE. If the two processes have no relationship, use ftok() to calculate an identifier (or define one).

int size is the size of this block of memory.

int flag is the mode (mode) and permission ID of this memory.

The mode can take the following values:

IPC_CREAT New (if it is created, it returns the current shared memory id)

IPC_EXCL is used in conjunction with IPC_CREAT, if it is created, it returns an error.

The “mode” and "permission identifier""""

如如: IPC_CREAT

Copyright © Windows knowledge All Rights Reserved