linux笔记之共享内存
来源:互联网 发布:net域名为什么遇冷 编辑:程序博客网 时间:2024/06/04 19:31
一.IPC之共享内存
1.进程间通信的三种方法:
- 消息队列
- 信号量
- 共享内存
2.共享内存的优点:
运行时省去了若干次拷贝,是以上三种程序间通信中最快的
3.共享内存的缺点
消息队列 管道等自带同步或互斥机制,而共享内存不自带,故需要使用信号量来实现共享内存的互斥和同步。
二.用代码实现共享内存
1.创建共享内存//int Creat_shm(int size)
创建代码调用的函数
以上图片中shmflg的参数若为2
的活则有内存则打开,无则创建,若为1和2
的话无则创建有则报错。
2获取代码//int Get_shm()
3.摧毁共享内存//int Destory_shm(int shmid)
摧毁内存调用的函数
4.其他函数
- 关联函数//
作用是将页表和物理内存的共享内存关联起来
- 去关联函数//
在页表中释放关联函数关联的地址
三.源代码
1.comm.h
#ifndef _COMM_H_#define _COMM_H_#include<errno.h>#include<sys/ipc.h>#include<sys/shm.h>#include<stdio.h>#include<sys/types.h>#define PATHNAME "."#define PROJ_ID 0x6666int Creat_shm(int size);int Get_shm();int Destory_shm(int shmid);#endif
2.comm.c
#include"comm.h"int comm_shm(int size,int flags){ int key=ftok(PATHNAME,PROJ_ID); if(key<0) { perror("ftok"); return -1; } int shmid=shmget(key,size,flags); if(shmid<0) { perror("shmid"); return -2; } return shmid;}int Creat_shm(int size){ return comm_shm(4096,IPC_CREAT|IPC_EXCL|0666);}int Get_shm(){ return comm_shm(0,IPC_CREAT);}int Destory_shm(int shmid){ if(shmctl(shmid,IPC_RMID,NULL)<0) { perror("shmctl"); return -1; }}
3.server.c
#include"comm.h"int main(){ int count=0; int shmid=Creat_shm(4096); sleep(5); char* sh_mat=shmat(shmid,NULL,0); sleep(5); while(count<4096) { sh_mat[count]='A'+count%26; sleep(1); count++; sh_mat[count]=0; } shmdt(sh_mat); sleep(5); Destory_shm(shmid); return 0;}
4.client.c
#include"comm.h"int main(){ int shmid = Get_shm(); sleep(5); char* shm_at=shmat(shmid,NULL,0); while(1) { printf("%s\n",shm_at); sleep(1); } shmdt(shm_at); return 0;}
四.运行结果图
0 0
- linux笔记之共享内存
- linux c语言学习笔记之IPC-共享内存
- Linux IPC之共享内存
- Linux通信之共享内存
- linux共享内存之mmap
- Linux IPC之共享内存
- Linux-IPC之共享内存
- Linux IPC之共享内存
- linux学习之共享内存
- 共享内存的实现---Linux内核笔记
- linux进程间通信之共享内存
- Linux进程间通讯之共享内存
- linux进程间通信之共享内存
- Linux编程之路---共享内存
- Linux进程间通讯之共享内存
- linux 进程通信之共享内存
- Linux进程间通信之共享内存
- Linux进程间通信之共享内存
- 几条常用命令
- struts2中的通配符映射
- tableView实现第一个cell半遮挡tableHeaderView
- JSTL
- github中ssh和https提交的区别
- linux笔记之共享内存
- linux命令行
- java第三天--cmd编译找不到符号解决及对象的转型
- cadence allegro 布线小技巧
- vmware workstation+ubuntu16.04突然不能联网了!
- 浏览器兼容之旅的第一站:如何创建条件样式
- hadoop自定义数据类型
- PHP7.1 狐教程
- 显著性检测的AC与MSSS算法