2
votes

This is my code:

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

I tried this too

    int fd=open("/home/victor/hello",O_WRONLY|0777);

but it's the same error:

Error mmapping the file: Permission denied

Doing ls -l | grep hola -rwxrwxrwx 1 victor victor 24 oct 24 01:47 hello

What's wrong?

1
AFAIK mmap()'s PROT_WRITE may imply PROT_READ, and PROT_READ is incompatible with an open() using O_WRONLY.Iwillnotexist Idonotexist
@IwillnotexistIdonotexist: Make that an answer. It's the right one.R.. GitHub STOP HELPING ICE
@Iwillnotexist Idonotexist Thank's! I change my open() O_WRONLY for O_RDWR and everything is fine!victor valentin

1 Answers

3
votes

From the glibc manual, and as already pointed out by R.. and Iwillnotexist Idonotexist above:

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