创建映射区等知识看上一篇:内存映射实现父子进程通信-CSDN博客
实验结果
这里因为手速原因,id 1~8被覆盖
大致过程:mmap_w.c先向p指针中写如数据 每次让id自增 然后sleep(1)
mmap_r.c 在p指针中读数据,打印到屏幕上
代码:
mmap_r.c:
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <fcntl.h> #include <sys/mman.h> #include <unistd.h> #include <errno.h> struct student { int id; int age; char name[256]; }; void sys_err(const char *str){ perror(str); exit(1); } int main(int argc,char *argv){ struct student stu; struct student *p; int fd; fd=open("test_map",O_RDONLY); if(fd==-1)sys_err("open error"); p=mmap(NULL,sizeof(stu),PROT_READ,MAP_SHARED,fd,0); if(p==MAP_FAILED)sys_err("mmap error"); close(fd); while(1){ printf("id=%d,name=%s,age=%d\n",p->id,p->name,p->age); sleep(1); } munmap(p,sizeof(stu)); return 0; }
mmap_w.c:
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <fcntl.h> #include <sys/mman.h> #include <unistd.h> #include <errno.h> struct student { int id; int age; char name[256]; }; void sys_err(const char *str){ perror(str); exit(1); } int main(int argc,char *argv){ struct student stu={1,23,"xiaoming"}; struct student *p; int fd; fd=open("test_map",O_RDWR|O_CREAT|O_TRUNC,0664); if(fd==-1)sys_err("open error"); ftruncate(fd,sizeof(stu)); p=mmap(NULL,sizeof(stu),PROT_READ|PROT_WRITE,MAP_SHARED,fd,0); if(p==MAP_FAILED)sys_err("mmap error"); close(fd); while(1){ memcpy(p,&stu,sizeof(stu)); stu.id++; sleep(1); } munmap(p,sizeof(stu)); return 0; }