c - 在C mmap文件中写入: Permission denied. Linux

标签 c linux file mmap

这是我的代码:

   #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 |格列普霍拉 -rwxrwxrwx 1 维克多 维克多 24 十月 24 01:47 你好

出了什么问题?

最佳答案

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

Note that most hardware designs cannot support write permission without read permission, and many do not distinguish read and execute permission. Thus, you may receive wider permissions than you ask for, and mappings of write-only files may be denied even if you do not use PROT_READ.

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

关于c - 在C mmap文件中写入: Permission denied. Linux,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33314745/

相关文章:

c - fprintf() 和 fputs() 没有得到正确的结果

c - n 个数字可能的三角形总数

objective-c - NSData 和 void * 之间的转换

c - Notepad++ 和 stdint.h 类型

php.ini 更改,但在 Ubuntu 上无效

linux - 测试使用 VFIO 的用户空间驱动程序?

linux - 线程 : some questions

Java解析文本文件并获取单词和字符之间的所有单词

java - 如何加载和解析 SVG 文档

具有多个 *.cpp 文件的 Linux 上的 C++ 生成文件