四十一. 使用mmap读取磁盘文件内容
这里是mmap.c
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <sys/mman.h>
#include <fcntl.h>
int main(int argc, const char* argv[])
{
int fd = open("english.txt", O_RDWR);
if(fd == -1)
{
perror("open error");
exit(1);
}
// get file length
// len > 0
int len = lseek(fd, 0, SEEK_END);
void * ptr = mmap(NULL, len, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if(ptr == MAP_FAILED)
{
perror("mmap error");
exit(1);
}
// 从内存中读数据
printf("buf = %s\n", (char*)ptr);
// ptr++;
munmap(ptr, len);
char buf[4096];
return 0;
}
四十二. mmap注意事项
四十三. 使用mmap进行有血缘关系的进程间通信
mmap_parent_child.c
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <string.h>
#include <sys/mman.h>
#include <fcntl.h>
int main(int argc, const char* argv[])
{
int fd = open("english.txt", O_RDWR);
if(fd == -1)
{
perror("open error");
exit(1);
}
// get file length
// len > 0
int len = lseek(fd, 0, SEEK_END);
void * ptr = mmap(NULL, len, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if(ptr == MAP_FAILED)
{
perror("mmap error");
exit(1);
}
close(fd);
// 创建子进程
pid_t pid = fork();
if(pid== -1)
{
perror("fork error");
exit(1);
}
if(pid>0)
{
//写数据
strcpy((char*)ptr,"你是我的儿子吗?");
//回收
wait(NULL);
}
else if(pid ==0)
{
//读数据
printf("%s\n",(char*)ptr);
}
// ptr++;
int ret = munmap(ptr, len);
if(ret == -1)
{
perror("munmap error");
exit(1);
}
return 0;
}
mmap的优势,在于数据是在内存,而非在磁盘里进行处理的
四十四. 创建匿名映射区
接下来,是anon_mmap.c
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <string.h>
#include <sys/mman.h>
#include <fcntl.h>
int main(int argc, const char* argv[])
{
//创建匿名内存映射区
int len = 4096;
//注意这里的参数的变化,
void * ptr = mmap(NULL, len, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANON, -1, 0);
if(ptr == MAP_FAILED)
{
perror("mmap error");
exit(1);
}
close(fd);
// 创建子进程
pid_t pid = fork();
if(pid== -1)
{
perror("fork error");
exit(1);
}
if(pid>0)
{
//写数据
strcpy((char*)ptr,"你是我的儿子吗?");
//回收
wait(NULL);
}
else if(pid ==0)
{
//读数据
printf("%s\n",(char*)ptr);
}
// ptr++;
int ret = munmap(ptr, len);
if(ret == -1)
{
perror("munmap error");
exit(1);
}
return 0;
}
相比较于前面,主要是加了MAP_ANON, 以及fd的位置用-1.
相当于父进程在内存中写了一句话,子进程在内存里读了出来。
四十五. mmap没有血缘关系的进程间通信思路