代码:mmap_w.c
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
struct Student{
int id;
char name[20];
int age;
};
void sys_err(char *str)
{
perror(str);
exit(1);
}
int main(int argc, char *argv[])
{
int fd;
struct Student stu = {1,"xiaoming",18};
struct Student *p;//用于接收mmap函数返回值
fd = open("testmap",O_RDWR|O_CREAT|O_TRUNC,0664);
if(fd==-1) sys_err("open");
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;
}
代码:mmap_r.c
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
struct Student{
int id;
char name[20];
int age;
};
void sys_err(char *str)
{
perror(str);
exit(1);
}
int main(int argc, char *argv[])
{
int fd;
struct Student stu;
struct Student *p;//用于接收mmap函数返回值
fd = open("testmap",O_RDONLY);
if(fd==-1) sys_err("open");
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;
}
结果: