Inter-process communication is completed through shared memory: shmget() shmat() shmdt()

1、shmget(2)

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

Function: Create an ID number for a shared memory area.
Parameters:
key: Get the value returned by the ftok() function.
Size: Shared memory block size, unit: Byte
shmglf: IPC_CREAT|0664 is generally used.
Return value:
success: id number
failure: -1
2, shmat(2)

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

Function: Obtain a shared memory area.
Parameters:
shmid: The return value of the shmget() function.
shmaddr: specify the allocated memory address, NULL means allocated by the system
shmflg:
RDONLY: read-only
0: read-write
Return value: success: the first address of the allocated shared memory
failure: (void *) -1

3、shmdt(2)

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

Function: Separate the mapping relationship.
Parameters: shmaddr: the first address of the shared memory that needs to be separated
Return value: Success: 0
Failure: -1

Example of code for sharing data between two processes through shared memory (writer):

int main(void){
    
    
    key_t key_id;
    key_id = ftok(FILENAME,PROJ_ID);
    int shm_id;
    shm_id = shmget(key_id,1,IPC_CREAT|0664);
    void *str_p = NULL;
    str_p = shmat(shm_id,NULL,0);
    printf("向共享内存写入数据\n");
    strcpy((char *)str_p,"write a data test");
    printf("写入内容:%s\n",(char *)str_p);
    printf("执行(shmdt(str_p)\n");
    shmdt(str_p);
    printf("读取共享内存区域数据。\n");
    printf("%s\n",(char*)str_p);
    return 0;
}

An example of two processes sharing data code through shared memory (reader):

#include <stdio.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#define FILENAME ".."
#define PROJ_ID  3
int main(void){
    
    
    key_t key_id;
    key_id = ftok(FILENAME,PROJ_ID);
    int shm_id;
    shm_id = shmget(key_id,1,IPC_CREAT|0664);
    void *str_p = NULL;
    str_p = shmat(shm_id,NULL,RDONLY);
    printf("读取共享内存数据:\n");
    printf("%s\n",(char*)str_p);
    printf("执行shmdt(str_p)\n");
    shmdt(str_p);
    printf("再次读取共享内存数据:\n");
    printf("%s\n",(char*)str_p);
    return 0;
}

Guess you like

Origin blog.csdn.net/weixin_47273317/article/details/105733283