#include <iostream>
#include <sys/mman.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
using namespace std;
int main()
{
// 1. 打开一个磁盘文件
int fd = open("/mnt/english.txt", O_RDWR);
if(fd == -1)
{
perror("open ");
exit(0);
}
// 2. 创建内存映射区
void* ptr = mmap(NULL, 4000, PROT_READ|PROT_WRITE,
MAP_SHARED, fd, 0);
if(ptr == MAP_FAILED)
{
perror("mmap");
exit(0);
}
// 3. 创建子进程
pid_t pid = fork();
if(pid > 0)
{
// 父进程, 写数据
const char* pt = "我是你爹, 你是我儿子吗???";
memcpy(ptr, pt, strlen(pt)+1);
}
else if(pid == 0)
{
cout<<"///"<<endl;
// 子进程, 读数据
usleep(3); // 内存映射区不阻塞, 为了让子进程读出数据
cout<<"data:"<<(char*)ptr<<endl;
cout<<"///"<<endl;
}
// 释放内存映射区
while(1);
munmap(ptr, 4000);
return 0;
}
//注
1.代码大部分引用自 https://subingwen.cn/linux/mmap/ 爱编程的大丙
2.创建的txt文件必须添加内容,否则运行结果为“总线错误”