【发布时间】:2015-10-24 05:08:17
【问题描述】:
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
int main()
{
int fd=open("/home/victor/hello",O_WRONLY);
if(fd<0)
{
perror("Open");
exit(EXIT_FAILURE);
}
struct stat sbuf;
if(fstat(fd, &sbuf)==-1){
perror("stat");
close(fd);
exit(EXIT_FAILURE);
}
void* file_memory= mmap(NULL, sbuf.st_size, PROT_WRITE, MAP_SHARED,fd,0);
if (file_memory == MAP_FAILED ) {
perror("Error mmapping the file");
close(fd);
exit(EXIT_FAILURE);
}
return 0;
}
我也试过了
int fd=open("/home/victor/hello",O_WRONLY|0777);
但这是同样的错误:
映射文件时出错:权限被拒绝
执行 ls -l | grep hola -rwxrwxrwx 1 victor victor 24 oct 24 01:47 你好
怎么了?
【问题讨论】:
-
AFAIK
mmap()的PROT_WRITE可能暗示PROT_READ,并且PROT_READ与使用O_WRONLY的open()不兼容。 -
@IwillnotexistIdonotexist:回答这个问题。这是正确的。
-
@Iwillnotexist Idonotexist 谢谢!我将我的 open() O_WRONLY 更改为 O_RDWR,一切都很好!