【问题标题】:In C mmap the file for write: Permission denied. Linux在 C mmap 中写入文件:权限被拒绝。 Linux
【发布时间】: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_WRONLYopen() 不兼容。
  • @IwillnotexistIdonotexist:回答这个问题。这是正确的。
  • @Iwillnotexist Idonotexist 谢谢!我将我的 open() O_WRONLY 更改为 O_RDWR,一切都很好!

标签: c linux file mmap


【解决方案1】:

来自 glibc 手册,正如上面 R..Iwillnotexist Idonotexist 已经指出的那样:

请注意,大多数硬件设计不支持写权限 没有读权限,很多不区分读和执行 允许。因此,您可能会获得比您要求的更广泛的权限, 即使您不使用,也可能会拒绝只写文件的映射 PROT_READ。

http://www.gnu.org/software/libc/manual/html_node/Memory_002dmapped-I_002fO.html

【讨论】:

    猜你喜欢
    • 2011-09-11
    • 1970-01-01
    • 2015-11-24
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 2018-08-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多