冠县网站建设,免费网课平台,东莞网站建设价位,html企业网站源码下载共享内存#xff1a;1、在内核中创建共享内存#xff1b;2、进程1和进程2都能够访问到#xff0c;通过这段内存空间进行数据传递#xff1b;3、共享内存是所有进程间通信方式中#xff0c;效率最高#xff0c;不需要在内核中往返进行拷贝#xff1b;4、共享内存的内存空…共享内存1、在内核中创建共享内存2、进程1和进程2都能够访问到通过这段内存空间进行数据传递3、共享内存是所有进程间通信方式中效率最高不需要在内核中往返进行拷贝4、共享内存的内存空间大小是4KB的整数倍常用的接口函数一、创建共享内存shmget函数 #include sys/ipc.h#include sys/shm.hint shmget(key_t key, size_t size, int shmflg);/*参数key键值key 通过ftok获取IPC_PRIVATE只能用于亲缘进程间的通信size共享内存的大小 PAGE_SIZE(4k)的整数倍shmflg共享的标志位IPC_CREAT|0666 或 IPC_CREAT|IPC_EXCL|0666返回值成功 共享内存编号失败 -1 重置错误码*/二、映射共享内存到当前的进程空间shmat函数 #include sys/ipc.h#include sys/shm.hvoid *shmat(int shmid, const void *shmaddr, int shmflg);/*参数shmid共享内存编号shmaddrNULL让系统自动分配shmflg共享内存操作方式0 读写SHM_RDONLY 只读返回值成功 指向共享内存的地址失败 (void *)-1 重置错误码*/三、取消地址映射shmdt函数 #include sys/ipc.h#include sys/shm.hint shmdt(const void *shmaddr);/*参数shmaddr指向共享内存的指针返回值成功 0失败 -1 重置错误码*/四、控制共享内存shmctl函数 #include sys/ipc.h#include sys/shm.hint shmctl(int shmid, int cmd, struct shmid_ds *buf);/*参数shmid共享内存编号cmd操作的命令码IPC_STAT获取IPC_SET设置IPC_RMID删除共享内存标记要销毁的段。实际上只有在最后一个进程将其分离之后 (关联结构shmid_ds的shm_nattch成员为零时) 段才会被销毁。调用者必须是段的所有者或创建者或具有特权。buf参数被忽略。buf共享内存属性结构体指针返回值成功 0失败 -1 重置错误码*/示例代码写端 #include stdio.h#include stdlib.h#include string.h#include sys/types.h#include sys/ipc.h#include sys/shm.h#include unistd.h#define PIGE_SIZE 4*1024int main(int argc, char const *argv[]){//获取键值key_t key ftok(/home/linux/work/MSG, k);if(-1 key){perror(ftok error);exit(1);}//创建共享内存int shmid shmget(key, 2*PIGE_SIZE,IPC_CREAT|0666);if(-1 shmid)\{perror(shmget error);exit(1);}//映射共享内存char *sh_addr (char *)shmat(shmid, NULL, 0);if((void *) -1 sh_addr){perror(shmat error);exit(1);}//向共享内存中写入数据while(1){fgets(sh_addr,128,stdin);sh_addr[strlen(sh_addr)-1] \0;if(!strncmp(sh_addr,quit,4)){break;}}//取消映射if(-1 shmdt(sh_addr)){perror(shmdt error);exit(1);}//删除共享内存if(-1 shmctl(shmid, IPC_RMID, NULL)){perror(shmctl error);exit(1);}return 0;}
读端 #include stdio.h#include stdlib.h#include string.h#include sys/types.h#include sys/ipc.h#include sys/shm.h#include unistd.h#define PIGE_SIZE 4*1024int main(int argc, char const *argv[]){//获取键值key_t key ftok(/home/linux/work/MSG, k);if(-1 key){perror(ftok error);exit(1);}//创建共享内存int shmid shmget(key, 2*PIGE_SIZE,IPC_CREAT|0666);if(-1 shmid)\{perror(shmget error);exit(1);}//映射共享内存char *sh_addr (char *)shmat(shmid, NULL, 0);if((void *) -1 sh_addr){perror(shmat error);exit(1);}while(1){sleep(2);//防止刷屏printf(%s\n,sh_addr);if(!strncmp(sh_addr,quit,4)){break;}}//取消映射if(-1 shmdt(sh_addr)){perror(shmdt error);exit(1);}//删除共享内存if(-1 shmctl(shmid, IPC_RMID, NULL)){perror(shmctl error);exit(1);}return 0;}
运行结果 linuxubuntu:~/work/MSG$ gcc w3.c -o w3linuxubuntu:~/work/MSG$ ./w3hihellochinaquitlinuxubuntu:~/work/MSG$ gcc r3.c -o r3linuxubuntu:~/work/MSG$ ./r3hihihihellochinachinachinaquitshmctl error: Invalid argument注意不按4k的整数倍给shmget传参分配时也是按4k的整数倍分配