Inter-process communication based on message queue and shared memory

Introduce

Master the principles of interprocess communication based on message queues and shared memory

experimental project

Inter-process communication based on message queue and shared memory

Purpose

1. Deepen the understanding of the concept of process, clarify the difference between process and program; further understand the essence of concurrent execution.
2. Master process management and process communication.
3. The process communication mechanism (IPC) of the Linux system allows large amounts of data to be exchanged between arbitrary processes.
4. The purpose of this experiment is to understand and be familiar with:
5. Message communication mechanism supported by Linux and its usage method
6. Principle and usage method of shared storage area of ​​Linux system.

Experimental preview

1. Message Queuing
1. Overview of Message Queuing:
Message Queuing is a linked list of messages, stored in memory and maintained by the kernel.
2. The characteristics of the
message queue : the message queue allows one or more processes to write or read messages to it, and each message has a type; the
message queue can implement random query of messages, and the messages do not have to be first-in, first-out Sequential reading, you can read according to the type of message when programming; just
like the unnamed pipe and the famous pipe, read the message from the message queue, the data in the message queue will be deleted.
The message in the message queue is also formatted;
the message will only be deleted when the kernel is restarted or manually deleted. If the message queue is not manually deleted, the message queue will always exist in memory; the
message queue identifier identifies the message queue. The message queue is throughout;
it is unique in the system.
Second, shared memory
Shared memory allows two or more processes to share a given storage area.
Shared memory is the fastest way to share data between processes. A process writes data to a shared memory area, and all processes that share this memory area can immediately see the contents.
The use of shared memory should pay attention to the mutual exclusion of access to a given storage area between multiple processes. If a process is writing data to the shared memory area, no other process should read or write the data before it completes this step.

Experimental content

First,
create a message queue, send and receive messages Create a message queue, call msgget (), msgsnd (), msggrev (), msgctrl () and other functions to send and receive messages between the two processes.
Second, the creation, attachment and disconnection of shared storage
Create shared memory, use shmget (), shmat (), shmctl (), shmctl () and other functions to achieve communication between the two processes.

experiment apparatus

Windows PC
Linux Ubuntu

Basic principle design instructions

First, the design principle:
In order to facilitate operation and observation results, a program is used as an "introduction", and two child processes, server and client, are created through the fork () function to communicate.
Second, the message queue: The
server establishes a message queue with a key of 75, waiting for messages sent by other processes. When a message of type 1 is encountered, it serves as an end signal, cancels the queue, and exits the Server. The server displays a sentence "(Server) received datetype (n) is:" after receiving a message; The
client uses a message queue with a key of 75 to send messages of type 10 to 1 successively, and then exits. The last message is the end signal required by the server. Each time the Client sends a message, it displays "(Client) sent datetype (n) is:"; the
parent process ends after both the server and client exit.
3. Shared memory: The
server establishes a message queue with a key of 75, waiting for messages sent by other processes. Each time the server receives a message, it displays a "(Server) received"; The
client uses a message queue with a key of 75 to receive messages in shared memory. Each time the Client sends a message, it displays a "(Client) sent"; the
parent process ends after both the server and client exit.

Experimental procedure

First, the message queue

1. Write a program and use the system call fork () to create two child processes server and client. The parent process waits for the two child processes to end and then exits.

#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
int main(int argc ,char *argv[])
{

	pid_t pid;
	pid = fork();	
	if(pid <0)
	{
		printf("fork error\n");
	}
	if(pid ==0)
	{			
	}
	else
	{		
		pid_t pid;
		pid = fork();
		if(pid <0)
		{
			printf("fork error\n");
		}
		if(pid ==0)
		{	    
		}
		}else{
			wait(NULL);
			sleep(1);
			printf("Main process quit\n");	
		}	
	}	
	return 0;
}

2. Create the message format structure of the message queue.

typedef struct _msg
{
	long msgtype;
	char m[500];

}MSG;

3. On the client side, create a message queue with a key value of 75, and send the string with the initial value of "abcdefghij" 10 times in a loop. After each sending, the pointer is shifted one bit to achieve a different effect for each content sent. At the same time, the message type of each sent message is decremented from 10 to 1. When the message with message type 1 is sent, the client side exits.

if(pid ==0)
	{
		int msgqid;
		int i = 0;
		msgqid = msgget(75,IPC_CREAT|0666);
		MSG msg;
		memset(msg.m,0,sizeof(msg.m));
		msg.msgtype = 10;
		char *a = "abcdefghij";
		for(;i < 11;i++)
		{
			strcpy(msg.m,a);
			sleep(1);
			msgsnd(msgqid,&msg,sizeof(msg.m),0);		
			printf("(Client)sent datetype %ld: %s\n",msg.msgtype,msg.m);
			msg.msgtype--;
			a++;
			if(msg.msgtype == 0 )
			{
				sleep(1);
				printf("Client sent over and shutdown now\n");
				exit(0);
			}
		}		
	}

4. On the server side, create a message queue with a key value of 75 and receive messages from the message queue in real time. The received message type is decremented from 10 to 1. After receiving the message with message type 1, the message queue is destroyed. The server side drop out.

if(pid ==0)
		{
	    int msgqid;
		int type = 10;
		msgqid = msgget(75,IPC_CREAT|0666);
		MSG msg;
		while(1)
		{
			msgrcv(msgqid,&msg,sizeof(msg.m),type,0);	
			printf("\t\t\t\t\t(Server)receiveddatetype %d: %s\n",type,msg.m);
			type--;
			if(type == 0)
			{
				msgctl(msgqid,IPC_RMID,NULL);
				sleep(1);
				printf("Sever get type 1 date and shutdown \n");
				sleep(1);
				printf("message queue destroyed\n");
				sleep(2);
				exit(0);
			}
		}

5. The running effect is as follows:
Insert picture description here

Second, shared memory

  1. Write a program, use the system call fork () to create two child processes server and client, the parent process waits for the two child processes to end and exit.
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/shm.h>
#include <sys/ipc.h>
#include <fcntl.h>
#include <string.h>
#define BUF 2048
int main(int argc,char *argv[])
{
	pid_t pid;
	pid = fork();
	if(pid < 0)
	{
		perror("fork error\n");
	}
	if(pid == 0)
	{	
		
	}
	else{
	    pid_t pid;
		pid = fork();
		if(pid < 0)
		{
			perror("fork error\n");
         	}
		if(pid == 0)
		{
		
		}
		else{	
			wait(NULL);
			sleep(2);
			printf("Process quit\n");
		    }	
	    }
	return 0;
}
  1. On the client side, create a shared memory with a key value of 75 and a size of 2048 that can be read and written. After the shared memory is mapped, the string with the initial value of "5201314" is sent 10 times in a loop, and the pointer is sent every time. Move back one bit to achieve a different effect each time the content is sent. Until the message with the content of "4" is sent, the client end naturally ends.
if(pid == 0)
	{	
		int shmid;
		int i = 0;
		char *a = "5201314";
		shmid = shmget(75,BUF,SHM_R|SHM_W|IPC_CREAT);
		char *shmadd;
		shmadd = shmat(shmid,NULL,0);
		bzero(shmadd,BUF);
		for(;i < 7;i++){
			sleep(1);
			bzero(shmadd,BUF);
			strcpy(shmadd,a);
			printf("(Client) sent: %s\n",shmadd);
			a++;
		     }
	}

3. On the server side and the client side, create a shared memory with a key value of 75 and a size of 2048 that can be read and written. After the shared memory is mapped, the message sent by the client in the shared memory is received in real time, and when the reception is completed After the message with the content of "4", unmap the shared memory, destroy the shared memory, and end the process.

if(pid == 0)
		{
		int shmid;
		shmid = shmget(75,BUF,SHM_R|SHM_W|IPC_CREAT);
		char *shmadd;
		shmadd = shmat(shmid,NULL,0);
		bzero(shmadd,BUF);
		while(1){
				sleep(1);
				printf("\t\t\t\t(Server) received: %s\n",shmadd);
				if(*shmadd == '4')
				{
					exit(0);
				}
			}
		shmdt(shmadd);
		shmctl(shmid,IPC_RMID,NULL);
		}

4. The running effect is as follows:
Insert picture description here

Analysis experience

Analysis: As long as you master the principles of process creation and control, message queue creation and related function calls, shared memory creation and related function calls, you can complete them step by step according to their respective communication principles .
Experience: Through hands-on operation of this experiment, I realized that Linux application design is indeed a highly operable course. Hands-on operation is to verify and master the theoretical knowledge of textbooks, strengthen my understanding of Ubuntu, and be more proficient in it The best way to perform operations is to experience the operation principles related to message queues and shared memory through personal operations, and gain a lot, which lays a solid foundation for future learning.

Experimental results

With the success of the test results, the creation and control of the process, the creation of the message queue and the inter-process communication, and the creation of the shared memory in the inter-process communication have all run successfully. The purpose of the experiment has been achieved and the experiment has been perfectly successful!

End

It is used here for organizing notes, the content is for reference only

Published 3 original articles · Likes0 · Visits 22

Guess you like

Origin blog.csdn.net/qq_43711326/article/details/105453454