MetallicPriest
MetallicPriest

Reputation: 30841

mmap with /dev/zero

Say I allocate a big memory (40MB) with mmap using /dev/zero as follows.

fd = open("/dev/zero", O_RDWR); 
a = mmap (0, 4096e4, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_FILE, fd, 0);

What I understand is that the kernel will initialize memories to zero as the pages are brought into the physical memory (I suppose the modern Linux kernels use Demand paging). So for example, when the first page is touched and therefore brought into the physical memory, kernel will initialize all of its 4096 bytes to zero, then when the second page is touched, it does the same and so on.

Is my understanding correct?

Upvotes: 17

Views: 11865

Answers (2)

Jiangtao Zhang
Jiangtao Zhang

Reputation: 89

Both mmap /dev/zero and ANONYMOUS don't have file backed, also zeroed content. Look at the following link http://man7.org/linux/man-pages/man2/mmap.2.html

Upvotes: -1

Jens Gustedt
Jens Gustedt

Reputation: 79003

Yes, even more the pages are only brought into existence if you touch them for the first time.

BTW, there is the flag MAP_ANONYMOUS that you can use in this situation, no need to open a file descriptor on /dev/null.

Upvotes: 14

Related Questions