首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 其他教程 > 操作系统 >

过程通信-共享内存 听课笔记

2012-07-18 
进程通信--共享内存 听课笔记多个进程共享一段物理内存是进程间共享数据最快的方法步骤1 创建共享内存, 使

进程通信--共享内存 听课笔记
多个进程共享一段物理内存
是进程间共享数据最快的方法

步骤
1 创建共享内存, 使用shmget函数
2 映射共享内存, 使用shmat函数, 将共享内存映射到具体的进程空间去
3 解除映射共享内存, 使用shmdt函数
4 删除共享内存, 使用shmctl函数

创建

#include <stdlib.h>#include <stdio.h>#include <string.h>#include <errno.h>#include <unistd.h>#include <sys/stat.h>#include <sys/types.h>#include <sys/ipc.h>#include <sys/shm.h>#define PERM S_IRUSR|S_IWUSR//共享内存可读可写/* 共享内存 */int main(int argc,char **argv) { int shmid; char *p_addr,*c_addr; if(argc!=2) { fprintf(stderr,"Usage:%s\n\a",argv[0]); exit(1); }/* 创建共享内存 */if((shmid=shmget(IPC_PRIVATE,1024,PERM))==-1) { fprintf(stderr,"Create Share Memory Error:%s\n\a",strerror(errno)); exit(1); } /* 创建子进程 */if(fork()) // 父进程写{ p_addr=shmat(shmid,0,0); memset(p_addr,'\0',1024); strncpy(p_addr,argv[1],1024);wait(NULL); // 释放资源,不关心终止状态exit(0); } else       // 子进程读{ sleep(1); // 暂停1秒c_addr=shmat(shmid,0,0); printf("Client get %p\n",c_addr); exit(0); } } 

热点排行