创建一个读文件 mmap_r.c
#include<stdio.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<string.h>
#include<stdlib.h>
#include<sys/mman.h>
struct STU{
int id;
char name[20];
char sex;
};
void sys_err(char *str)
{
perror(str);
exit(1);
}
int main(int argc,char *argv[])
{
int fd;
struct STU student;
struct STU *mm;
if(argc < 2){
printf("./a.out file_shared\n");
exit(-1);
}
fd = open(argv[1],O_RDONLY);
if (fd == -1)
sys_err("open error");
mm = mmap(NULL,sizeof(student),PROT_READ,MAP_SHARED,fd,0);
if (mm == MAP_FAILED)
sys_err("mmap error");
close(fd);
while (1) {
printf("id=%d\tname=%s\t%c\n", mm->id, mm->name, mm->sex);
sleep(2);
}
munmap(mm, sizeof(student));
return 0;
}
创建一个写文件 mmap_w.c
#include<stdio.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<string.h>
#include<stdlib.h>
#include<sys/mman.h>
struct STU{
int id;
char name[20];
char sex;
};
void sys_err(char *str)
{
perror(str);
exit(1);
}
int main(int argc,char *argv[])
{
int fd;
struct STU student = {10, "xiaoming", 'm'};
struct STU *mm;
if(argc < 2){
printf("./a.out file_shared\n");
exit(-1);
}
fd = open(argv[1],O_RDWR | O_CREAT, 0664);
ftruncate(fd,sizeof(student));
mm = mmap(NULL, sizeof(student), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
if (mm == MAP_FAILED)
sys_err("mmap error");
close(fd);
while (1) {
memcpy(mm, &student, sizeof(student));
student.id++;
sleep(1);
}
munmap(mm, sizeof(student));
return 0;
}
创建一个共享文件 file_shared
1.分别编译两个文件
2.先执行写文件 ./mmap_w file_shared
3.再打开一个终端,执行读文件 ./mmap_r file_shared
从结果可以看出,写端一直在覆盖原来的id,读端一直在读取file_shared中的内容。