linux笔记之共享内存
2017-03-15 23:05
239 查看
一.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 0x6666 int 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; }
四.运行结果图
相关文章推荐
- Linux程序设计笔记(第14章 信号量、共享内存和消息队列)
- Linux进程间通信——IPC共享内存学习笔记
- Linux程序设计学习笔记----System V进程通信(共享内存)
- linux 进程学习笔记-共享内存
- 【linux高级环境编程学习笔记三】共享内存通信
- Linux 驱动学习笔记05--字符驱动实例,实现一个共享内存设备的驱动
- Linux笔记_进程通讯——共享内存
- 嵌入式linux的学习笔记-共享内存(六)
- Linux学习笔记27——共享内存
- Linux中共享内存及内存映射技术研究
- Linux环境进程间通信(五): 共享内存(上)
- Linux环境进程间通信(五): 共享内存(上)
- Linux环境进程间通信 共享内存
- Linux环境进程间通信(五): 共享内存(下)
- linux 文件操作函数 通过例子来解释 父子间文件描述符共享 内存映像图
- 将 Win32 C/C++ 应用程序迁移到 POWER 上的 Linux,第 1 部分: 进程、线程和共享内存服务 (转)
- Linux环境进程间通信(五): 共享内存(下)
- Linux环境进程间通信(五): 共享内存(上)
- Linux环境进程间通信(五): 共享内存(下)
- Linux中共享内存及内存映射技术研究