Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
254 views
in Technique[技术] by (71.8m points)

linux - Write-only mapping a O_WRONLY opened file supposed to work?

Is mmap() supposed to be able to create a write-only mapping of a O_WRONLY opened file?

I am asking because following fails on a Linux 4.0.4 x86-64 system (strace log):

mkdir("test", 0700)          = 0
open("test/foo", O_WRONLY|O_CREAT, 0666) = 3
ftruncate(3, 11)                        = 0
mmap(NULL, 11, PROT_WRITE, MAP_SHARED, 3, 0) = -1 EACCES (Permission denied)

The errno equals EACCESS.

Replacing the open-flag O_WRONLY with O_RDWR yields a successful mapping.

The Linux mmap man page documents the errno as:

   EACCES A  file descriptor refers to a non-regular file.  Or a file map‐
          ping was  requested,  but  fd  is  not  open  for  reading.   Or
          MAP_SHARED  was  requested  and PROT_WRITE is set, but fd is not
          open in read/write (O_RDWR) mode.  Or PROT_WRITE is set, but the
          file is append-only.

Thus, that behaviour is documented with the second sentence.

But what is the reason behind it?

Is it allowed by POSIX?

Is it a kernel or a library limitation? (On a quick glance, I couldn't find anything obvious in Linux/mm/mmap.c)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I don't think the x86 hardware supports write-only pages, so write access implies read. But it seems to be a more general requirement than just x86 - mm/mmap.c contains this code in do_mmap_pgoff():

    case MAP_SHARED:
        if ((prot&PROT_WRITE) && !(file->f_mode&FMODE_WRITE))
            return -EACCES;
        ....
        /* fall through */
    case MAP_PRIVATE:
        if (!(file->f_mode & FMODE_READ))
            return -EACCES;

I think that explains what you're seeing.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...