创建了一个修改字节文件的简单 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/