c - 使用mmap修改文件时出现权限错误

标签 c linux

创建了一个修改字节文件的简单 mmap 程序。 在一个简单/小文件上以 root 身份运行它,出现错误

# ./a.out tmp.txt 92
fd=3
mmap: Permission denied

代码片段

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/mman.h>

int main(int argc, char *argv[]) {
    int fd = open(argv[1], O_WRONLY);
    printf("fd=%d\n", fd);
    char *p = mmap(0, 0x1000, PROT_WRITE, MAP_SHARED, fd, 0);
    if (p == MAP_FAILED) {
        perror ("mmap");
        return 1;
    }
    p[0] = 0xde;
    close(fd);
    return 0;
}

想知道哪里出了问题。谢谢。

更新1 修复了代码片段中的错字,我打算在那里使用 PROT_WRITE

最佳答案

来自 mmap 的手册页:

EACCES A file descriptor refers to a non-regular file. Or a file mapping was requested, but fd is not open for reading. Or MAP_SHARED was requested and PROT_WRITE is set, but fd is not open in read/write (O_RDWR) mode. Or PROT_WRITE is set, but the file is append-only.

因此,为了映射文件 MAP_SHARED,您需要以读/写模式打开它,而不是只写。这是有道理的,因为需要读取文件的内容来初始化您不写入的内存部分。

此外,IA-32 不允许页的只写映射,因此在这样的机器上使用 PROT_WRITE 映射将隐含地也启用 PROT_READ,因此会失败对于不可读的文件描述符。

关于c - 使用mmap修改文件时出现权限错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42193063/

相关文章:

php - 带有预装扩展的 Joomla

c - strtok 没有遍历所有标记

c - 这个值分配是如何工作的?

c - Tree satisfiing BST property 但我认为它不是BST?

c - 当一个进程调用 sleep 函数时,它会发出信号吗?

c - 如何从 C 中的字符串中删除回车?

c - 在 C/Linux 中使用命名管道和 fork

c++ - C/C++ Cyanogenmod 如何使用不同版本的工具链编译内核?

c++ - 在 Linux mint 中使用 g++ 导致对 'Class::Function' 的 undefined reference (collect2 : error)

linux - centos 7 上启动时加载 rc.local