内存映射的注意事项

1.如果对mmap的返回值(ptr)做++操作(ptr++),munmap是否能够成功?
    可以,但是不建议

2.如果open时O_RDONLY,mmap时prot参数指定PROT READPROT WRITE会怎样?
    错误,返回MAP_FAILED open()函数中的权限建议和prot参数的权限保持一致

3.如果文件偏移量为1000会怎样?
    必须是1024的整数倍,返回MAP_FAILED

4.mmap什么情况下会调用失败?
    -第一个参数length = 0
    -第三个参数prot 只指定了写权限


5.可以open的时候O_CREAT一个新文件来创建映射区吗?
    -可以,但是创建的文件大小如果为0,肯定不行
    -可以对新文件进行扩展
        -lseek()
        -truncate

6.mmap后关闭文件描述符,对mmap映射有没有影响?
    映射区还存在,创建映射区的fd被关闭,没有任何影响

7.对ptr越界操作会怎样?
    会出现段错误

使用内存映射实现文件拷贝功能

    思路:

        1.对原始的文件进行内存映射

        2.创建新文件,要进行扩展

        3.新文件进行内存映射

        4.通过内存拷贝将第一个文件的内存数据拷贝到新的文件内存中

        5.释放资源

#include<stdio.h>
#include<sys/mman.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<string.h>
#include<unistd.h>
#include<stdlib.h>
int main() {
    //1
    int fd = open("english.txt", O_RDWR);
    //2.
    int fd1 = open("cpy.txt", O_RDWR | O_CREAT, 0664);
    int size = lseek(fd, 0, SEEK_END);
    truncate("cpy.txt", size);
    write(fd1, " ", 1);
    //3.
    void * ptr = mmap(NULL, size, PROT_WRITE | PROT_READ, MAP_SHARED, fd, 0);
    void * ptr1 = mmap(NULL, size, PROT_WRITE | PROT_READ, MAP_SHARED, fd1, 0);
    //4.
    memcpy(ptr1, ptr, size);
    munmap(ptr1, size);
    munmap(ptr, size);
    close(fd1);
    close(fd);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/ME_Liao_2022/article/details/133243711
今日推荐