2015-10-24 138 views
2

這是我的代碼:在C mmap中寫入文件:Permission denied。 Linux的

#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); 

但它同樣的錯誤:

錯誤mmapping文件:權限被拒絕

做ls -l | grep hola -rwxrwxrwx 1勝者勝者24 oct 24 01:47你好

怎麼了?

+6

AFAIK'MMAP()'的'PROT_WRITE'可以暗示'PROT_READ','PROT_READ'與'open()'不兼容,使用'O_WRONLY'。 –

+2

@IwillnotexistIdonotexist:做出答案。這是正確的。 –

+1

@Iwillnotexist Idonotexist謝謝! 我改變了我的open()O_WRONLY for O_RDWR,一切都很好! –

回答

3

從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

相關問題