目录
1、案例系统的结构
1.1结构框图
1.2进程间通信
1、管道技术:有名管道、无名管道(有序)
2、SystemV IPC:消息队列、共享内存、信号量
本例采用共享内存的方法来做。
2、案例实现
监控器:名称:(机房1,机房2,……)
温度值:36.32 27.23
2.1案例进程间通信数据结构
task.h
#ifndef DAY4_TASK_H
#define DAY4_TASK_H
#define MAX_TASK 5
//一条记录
struct task_msg{
double temp;
char label[32];
};
struct tasks_info{
int num;
struct task_msg data[MAX_TASK];
};
#define KEY_1 "/home"
#define KEY_2 10
/* 初始化共享内存空间,返回对应进程的用户空间映射的地址*/
extern void* init_shm(void);
extern void detach_shm(void *p);
#endif //DAY4_TASK_H
2.1.1共享内存操作基础理论
system V IPC
1、寻找key值 寻找通信双方可以识别的key ftok 获得key值
2、通过key找到找到对应的IPC对象(共享内存)shmget 获得ID值
3、在进程的应用空间中映射内核IPC对象的地址(该进程的用户空间地址)shmat/shmdt
4、把应用空间的地址转换为共享双方约定的数据结构进行填充和读取
2.1.2共享内存操作案例
sim_catch.c
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <time.h>
#include <string.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include "task.h"
static struct tasks_info *tasks;
static char* task_lables[]={"机房1","机房2","机房3","机房4","机房5"};
//发送端
/*void init_shm(){
key_t k1;
int shm_id;
struct task_info *t1;
k1=ftok("/home",10);
if(k1==-1){
return NULL;
}
shm_id=shmget(k1,sizeof(struct task_info),IPC_CREAT | 0644);
if(shm_id==-1){
return NULL;
}
t1=(struct task_info *)shmat(shm_id,NULL,0);
t1-&