The seventh experiment of Linux operating system experiment series-inter-process communication-creation, attachment and disconnection of shared storage area

1. The purpose of the experiment
Understand and familiarize yourself with the shared storage mechanism

2. Experimental content:

Compile a program for sending and receiving a shared memory area 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) SERVER establishes a shared area with key 75, and sets the first byte to -1. As a sign that the data is empty. Waiting for messages from other processes. When the value of the byte changes, it means that the message has been received and processed. Then set its value to -1 again. If the value encountered is 0, it is regarded as an end signal, the queue is cancelled, and the SERVER is exited. SERVER displays "(server)receive" every time it receives a piece of data.
(3) The CLIENT side creates a shared area with a key of 75. When the first byte obtained by the share is -1, the Server side is idle and can send requests. CLIENT then fills in 9 to 0. During this period, wait for the server to be idle again. After performing these operations, CLIENT exits. "(Client) sent" is displayed after CLIENT sends out data every time.
(4) The parent process ends after both SERVER and CLIENT exit.

Three, the experimental environment

Linux operating system

Fourth, the experimental process and operating results

源代码:
#include<stdlib.h>
#include<unistd.h>
#include<stdio.h>
#include<wait.h>
#include<sys/types.h>
#include<sys/msg.h>
#include<sys/ipc.h>
#include <sys/shm.h>
#define SHMKEY 75 /定义共享区关键词/
int shmid,i;
int *addr;

void CLIENT()
{ int i; shmid=shmget(SHMKEY,1024,0777); / Get shared area, length 1024, keyword SHMKEY / addr=shmat(shmid,0,0); / Start address of shared area is addr / for(i=9;i>=0;i–) { while(*addr!= -1); printf("(client)sent\n"); / print(client)sent / *addr=i; / Assign i to addr / } exit(0); }










void SERVER()
{ shmid=shmget(SHMKEY,1024,0777|IPC_CREAT); / Create a shared area / addr=shmat(shmid,0,0); /The starting address of the shared area is addr / do { *addr=-1 ; while(*addr==-1); printf("(server)received\n"); / service process uses shared area / } while(*addr); shmctl(shmid,IPC_RMID,0); exit(0) ; }











int main()
{
if(fork())
SERVER();
if(fork())
CLIENT();
wait(0);
wait(0);
}

Result graph:
Insert picture description here

Guess you like

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