What is the difference between calling mmap() on a disk file before or after a fork?

后端 未结 1 661
花落未央
花落未央 2021-01-20 13:20

I\'ve been working on understanding how mmap() works with disk-backed files, and am mostly getting it, but I still have this question.

In a situation with a master p

1条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-20 14:11

    It makes no difference to page fault activity. The page map of a file is global to the OS, it says whether a particular page is in RAM or not. The PTE of every process that has the file mapped points to this common data structure. There will only be a page fault for the first process that tries to access a page that isn't in RAM. That will trigger it to be read in, and other processes that try to access the same page will be able to use that RAM.

    One difference between the two scenarios is whether the virtual addresses assigned to the mapped block are the same. If you call mmap before forking, the address will be copied in all the children. If you call mmap after forking, they could get different addresses. Using the same address in all processes allows you to pass pointers into the mapped block between the processes if you want. You can have pointers between objects within the block. If they're not all at the same address, you need to use offsets, and the processes will all have to add the offsets to the base address.

    0 讨论(0)
提交回复
热议问题