Linux remote development - (IPC communication) use of shared memory

content

I. Introduction

Second, what is shared memory

Third, the creation and use of shared memory

1. shmget() function

2. shmat() function

3. shmdt() function

Fourth, use shared memory to achieve inter-process communication

1. Prepare a write end

2. Prepare a reader

3. Test results


I. Introduction

        Interprocess communication (IPC, InterProcess Communication) refers to the dissemination or exchange of information between different processes. Now the interprocess communication methods used by linux are: (1) pipes (pipe) and named pipes (FIFO) (2) signals ( signal) (3) message queue (4) shared memory (5) semaphore (6) socket (socket).

        Signals and pipes were introduced before. Today, let's learn how shared memory communicates between processes.

Second, what is shared memory

  • Shared memory diagram

View source image

        Shared memory is a special address range created by IPC for a process. It will appear in the process's address space. Other processes can "connect" the same shared memory segment to their own address space. As shown in FIG.

Note:

: Shared memory can be created by a process, but shared memory does not belong to any process

: Shared memory belongs to the operating system and is managed by the operating system

: All processes can access shared memory addresses as if they were malloc allocated

: If a process writes data to this shared memory, the changes will be immediately seen by other processes that have access to the same shared memory

  • Enter the command in the linux terminal: ipcs can view the message queue, shared memory segment, and signal number group of the current system

        The maximum transfer size of the named pipe FIFO used before is 65535 bytes, and the fifo "file" used is easily deleted by the user, which will cause communication errors between processes . Shared memory allows two unrelated processes to access The same part of logical memory is very efficient , so let's introduce how shared memory is created and used in code.

Third, the creation and use of shared memory

1. shmget() function

  • Function: Create shared memory (not exist) or get shared memory (exist).

#include <sys/ipc.h>
#include <sys/shm.h>

Function prototype :

int shmget(key_t key, size_t size, int shmflg);

Parameters :

key: (non-zero integer), which effectively names the shared memory segment

size: the amount of memory that needs to be shared

shmflg: consists of nine permission flags, their usage is the same as the mode flag used when creating files

Return value :

If the shared memory is created successfully, a non-negative integer is returned, that is, the identification code of this segment of shared memory;

Returns -1 on failure.

 Example:

  • create a shared memory
#include <iostream>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>

using namespace std;

int main()
{
	int shmid = 0;
	//不存在则创建共享内存,存在则获取
	shmid = shmget((key_t)1001, 10086, IPC_CREAT | 0777);
	if (shmid < 0)
	{
		perror("shmget error");
	}
	else
	{
		cout << "创建共享内存成功" << endl;
	}

	return 0;
}
  • Through the command: ipcs, you can see our newly created shared memory segment with a permission of 777 and a number of bytes of 10086.

  • ipcrm -m shmid delete shared memory
  • Ipcrm -a deletes all except the memory segment originally created by the root of the system

Delete the shared memory created in the previous step through the ipcrm command 

2. shmat() function

  • Function: When the shared memory is created for the first time, it cannot be accessed by any process. The function of the shmat() function is to start the access to the shared memory and connect the shared memory to the address space of the current process.

#include <sys/types.h>
#include <sys/shm.h>

Function prototype :

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

Parameters :

shmid: shared memory identifier returned by the shmget() function

shmaddr: the address where the shared memory is going to be placed when it is connected to the current process

shmflg: can be specified as 0,

Return value :

Success: return a pointer, the pointer points to the first byte of the shared memory, which is the first address of the shared memory

Failure: -1 is returned.

3. shmdt() function

  • Function: separate the shared memory from the current process

#include <sys/types.h>
#include <sys/shm.h>

Function prototype :

int shmdt(const void *shmaddr);

Parameters :

shmaddr: the address pointer returned by the shmat() function

Return value :

success: return 0,

Failure: return -1.

Note:

: Using the shmdt() function to get out of shared memory does not mean deleting it, just that the current process can no longer access it.

Fourth, use shared memory to achieve inter-process communication

The following is a small example to use shared memory to implement simple communication between two unrelated processes.

1. Prepare a write end

  • Write data to shared memory, the data written is { "10001", "admin" };
#include <iostream>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <string.h>
using namespace std;

typedef struct student
{
	char id[10];
	char name[10];
}STU;

int main()
{
	STU stu = { "10001","admin" };
	void* shamdaddr = NULL;
	int shmid = 0;
	//不存在则创建共享内存,存在则获取
	shmid = shmget((key_t)1001, 10086, IPC_CREAT | 0777);
	if (shmid < 0)
	{
		perror("shmget error");
	}
	else
	{
		//连接共享内存,首地址存到 shamdaddr
		shamdaddr = shmat(shmid, NULL, 0);
		memcpy(shamdaddr, &stu, sizeof(STU));//内存拷贝 即:将stu结构体的数据写入共享内存中
		cout << "写入数据成功" << endl;
		//结束连接 当前进程脱离共享内存
		shmdt(shamdaddr);
	}
	return 0;
}

2. Prepare a reader

  • Read data from shared memory and store it in an empty structure.
#include <iostream>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <string.h>
using namespace std;

typedef struct student
{
	char id[10];
	char name[10];
}STU;

int main()
{
	STU stu = { 0 };
	void* shamdaddr = NULL;
	int shmid = 0;
	//不存在则创建共享内存,存在则获取
	shmid = shmget((key_t)1001, 10086, IPC_CREAT | 0777);
	if (shmid < 0)
	{
		perror("shmget error");
	}
	else
	{
		//连接共享内存,首地址存到 shamdaddr
		shamdaddr = shmat(shmid, NULL, 0);
		memcpy(&stu, shamdaddr, sizeof(stu)); //内存拷贝 即:将共享内存中的数据写入空的结构体中
		cout << "获取数据成功" << endl;
		cout << stu.id << endl;
		cout << stu.name << endl;
		//结束连接 当前进程脱离共享内存
		shmdt(shamdaddr);
	}
	return 0;
}

 The code of the two projects is similar, the difference is that one writes data and the other reads data.

3. Test results

  • Compiled by g++ under linux, and run in ./ mode, the test results are as follows

normal read and write 

The shared memory segment is also created normally, and the number of connections is 0, because the program has ended.

The data in the shared memory will always exist without modification, and the content can be read repeatedly.

Originality is not easy, please indicate the source when reprinting.

If it is helpful to you, you can click three times, and it will be updated continuously (hee hee).

Guess you like

Origin blog.csdn.net/wmcy123/article/details/123718935