进程通信之共享内存

  

共享内存是进程间通信方式中效率最高的,由内核创建,少了两次拷贝,直接操作共享内存。

优点:高效。

缺点:不提供同步与互斥。

,//comm.h   1,才能# include   2,才能# include   3,才能# include   4,才能# include   5,才能# include   6,才能# include   7,才能# include   8,才能# define  _PATH_ “。”   9,才能# define  x757 _PROJ_ID_  0   ,10 # define  _SIZE_  4 * 1024   ,11 static  int  shm (int  size_t 规模;旗帜);   ,12 int  creat_shm (size_t 大小);   ,13 int  get_shm (size_t 大小);   ,14 void *, at_shm (int  shm_id);   ,15 int  dt_shm (void * const  shmadd);   ,16 int  destory_shm (int  shm_id);//comm.c   1,#才能包括“comm.h”   2,才能static  int  _shm (size_t ,大小,int 旗帜)   3,{才能   4,,,,,,,key_t  _key=ftok (_PATH_ _PROJ_ID_);   5,,,,,,,如果(_key<0)   6,,,,,,,{   7,,,,,,,,,,,perror (“ftok”);   8,,,,,,,,,,,return  1;   9,,,,,,,}   ,10个,,,,int  shm_id=shmget (_key、大小、旗帜);   ,11,,,,如果(shm_id<0)   ,12,,,,{   ,13,,,,,,,,perror (“shmget”);   ,14日,,,,,,,,return  1;   ,15,,,,}   ,16岁,,,,return  shm_id;   ,17}   ,18 int  creat_shm (size_t 大小)   ,19日{   ,20,,,,return  _shm(大小、IPC_CREAT | IPC_EXCL | 0666);   ,21}   ,22 int  get_shm (size_t 大小)   ,23日{   ,24岁,,,,return  _shm(大小、IPC_CREAT);   ,25}   ,26 void *, at_shm (int  shm_id)   ,27日{   ,28岁,,,,return 调用shmat (shm_id零0);   ,29}   ,30 int  dt_shm (void * const  shmadd)   ,31日{   ,32岁,,,,return  shmdt (shmadd);   ,33}   ,34 int  destory_shm (int  shm_id)   ,35 {   ,36,,,,如果(shmctl (shm_id IPC_RMID, NULL) & lt; 0)   ,37岁,,,,{   ,38岁,,,,,,,,perror (“shmctl”);   ,39岁,,,,,,,,return  1;   ,40岁,,,,}   ,41岁,,,,return  0;   ,42}//server.c   1,#才能包括“comm.h”   2,才能int 主要()   3,{才能   4,,,,,,,int  shm_id=creat_shm (_SIZE_);   5,,,,,,,char *, buf=(char *) at_shm (shm_id);   6,,,,,,,//memset (buf, ' \ 0 ', _SIZE_);   7,,,,,,,,(1)   8,,,,,,,{   9,,,,,,,,,,,printf (" % s \ n ",但);   ,10个,,,,,,,,睡眠(1);   ,11,,,,}   ,12,,,,dt_shm (buf);   ,13,,,,挂(buf);   ,14}//client.c   1,#才能包括“comm.h”   2,才能int 主要()   3,{才能   4,,,,,,,int  shm_id=get_shm (_SIZE_);   5,,,,,,,如果(shm_id<0)   6,,,,,,,{   7,,,,,,,,,,,printf (" get_shm 错误\ n ");   8,,,,,,,,,,,return  1;   9,,,,,,,}   ,10个,,,,char *, buf=(char *) at_shm (shm_id);   ,11,,,,memset (buf, ' \ 0 ', _SIZE_);   ,12,,,,int 我=0;   ,13,,,,而(i<_SIZE_-1)   ,14日,,,,{   ,15,,,,,,,,睡眠(1);   ,16岁,,,,,,,,但我+ +=' A ';   ,17岁,,,,}   ,18岁,,,,dt_shm (buf);   ,19岁,,,,return  0;   ,20}//Makefile   1,才能.PHONY:所有   2,才能:server 客户端   3,才能服务器:server.c  comm.c   4,,,,,,,gcc  -o  $ @  $ ^   null   null   null   null   null   null   null   null   null   null   null   null   null

进程通信之共享内存