Linux operating system experiment series of experiment six inter-process communication-messages

1. The purpose of the experiment
1. To understand what a message is
2. To be familiar with the mechanism of message transmission

2. Experimental content:
creation, sending and receiving of messages. Use the system calls msgget( ), msgsnd( ), msgrev( ), and msgctl() to compile a program for sending and receiving messages with a length of 1k.

Program design
(1) In order to facilitate the operation and observation of the results, a program is used as the "introduction", and two sub-processes of fork(), SERVER and CLIENT, are used for communication.
(2) The SERVER side establishes a message queue with a key of 75 and waits for messages from other processes. When a message of type 1 is encountered, it will be used as an end signal to cancel the queue and exit the SERVER. SERVER displays "(server)received" every time it receives a message.
(3) The CLIENT end uses the message queue with key 75, sends messages of type 10 to 1, and then exits. The last message is the end signal required by the SERVER. "(Client) sent" is displayed after CLIENT sends out a message.
The parent process ends after both SERVER and CLIENT exit.

3. Experimental environment
Linux operating system

4. Experimental process and running results
Source code:
#include<stdio.h>
#include<sys/msg.h>
#include<sys/ipc.h>
#include<sys/types.h>
#include<stdlib.h >
#define msgkey 75

struct msgform
{
long msgtype;
char msgtext[1000];
}msg;

int msgqid,i;

void cilent(){
int i;
msgqid=msgget(msgkey,0777);
for(i=10;i>=1;i–){
msg.msgtype=i;
printf("(cilent)send\n");
msgsnd(msgqid,&msg,1000,0);
}
exit(0);
}

void server(){
msgqid=msgget(msgkey,0777|IPC_CREAT);
do{
msgrcv(msgqid,&msg,1000,0,0);
printf("(server) received\n");
msgsnd(msgqid,&msg,sizeof(int),0);
}while(msg.msgtype!=1);
msgctl(msgqid,IPC_RMID,0);
exit(0);
}

main(){
while((i=fork())-1);
if(!i) server();
while((i=fork())
-1);
if(!i) cilent();
wait(0);
wait(0);
}

Result graph:
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_43372169/article/details/110521821