Invalid argument in mmap

0

I want to write to the file "server.log" and when compiling the code, the result is "Invalid argument" in the function "mmap".

 void MMP(){
    char* addr;
    int fd;
    struct stat sb;

    fd = open("server.log", O_WRONLY | O_CREAT, 0700);

    //para obter o tamanho do ficheiro
    if(fd == -1){
        perror("Erro na abertura do ficheiro server.log");
        exit(1);
    }

    if(fstat(fd, &sb) == -1){
        perror("Erro no stat");
        exit(1);
    }

    addr = mmap((caddr_t)0, sb.st_size, PROT_WRITE, MAP_PRIVATE, fd, 0);
    if(addr == -1){
       perror("Erro no mapeamento do ficheiro em memória partilhada");
       exit(-1);
    }

}
    
asked by anonymous 25.11.2016 / 01:11

1 answer

0

First we have to make clear some things:

  • Use void for the variable addr
  • Open the file with Read and Write enabled ( O_RDWR ). This is necessary for mmap () to map.
  • In the mode open permissions, to create the file use S_IRWXU instead of 0700 in>.
  • If the size of server.log is zero, to write to the file you need to increase it (and mmap () does not accept length in> equal to zero). (see next item)
  • There is a problem with you using the MAP_PRIVATE argument in mmap () : With MAP_PRIVATE , as it says in the user@host:~$ man 2 mmap manual, what you type in the mapped region will not be written to server.log file; and also only your process has access to the mapped region (not shared). To write to server.log as much as to have the shared mapping, you need to use MAP_SHARED , whose implementation is a bit different and I'll show it below.
  • If offset is nonzero, it needs to be a multiple of the value returned when you call the sysconf (_SC_PAGE_SIZE) function.
  • Compare addr with MAP_FAILED instead of -1 .
  • Remember to close the close (fd) file and also "demap" it with munmap (addr, mapped region size) .
  • And also remember to include all the headers needed at the beginning of the code.

In case of doubt:

open prototype
int open(const char *pathname, int flags, mode_t mode);

mmap ()

25.11.2016 / 22:57