简体   繁体   中英

mmap() owning memory block

I have a call to mmap() which I try to map 64MB using MAP_ANONYMOUS as follows:

void *block = mmap(0, 67108864, PROT_READ, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (block == MAP_FAILED)
    exit(1);

I understand that to actually own the memory, I need to hit that block of memory. I want to add some sort of 0's or empty strings to actually own the memory. How would I do that? I tried the following, but that obviously segfaults (I know why it does):

char *temp = block;
for (int i = 0; i < 67108864; i++) {
    *temp = '0';
    temp++;
}

How would I actually gain ownership of that block by assigning something in that block?

Thanks!

Your process already owns the memory, but what I think you want is to make it resident. That is, you want the kernel to allocate physical memory for the mmap ed region.

The kernel allocates a virtual memory area (VMA) for the process, but this just specifies a valid region and doesn't actually allocate physical pages (or frames as they are also sometimes called). To make the kernel allocate entries in the page table, all you need to do is force a page fault.

The easiest way to force a page fault is to touch the memory just like you're doing. Though, because your page size is almost certainly 4096 bytes, you really only need to read one byte every 4096 bytes thereby reducing the amount of work you actually need to do.

Finally, because you are setting the pages PROT_READ , you will actually want to read from each page rather than try to write.

Your question is not very well formulated. I don't understand why you think the process is not owning its memory obtained thru mmap ?

Your newly mmap -ed memory zone has only PROT_READ (so you can just read the zeros inside) and you need that to be PROT_READ|PROT_WRITE to be able to write inside.

But your process already "owns" the memory once the mmap returned.

If the process has pid 1234, you could sequentially read (perhaps with cat /proc/1234/maps in a different terminal) its memory map thru /proc/1234/maps ; from inside your process, use /proc/self/maps .

Maybe you are interested in memory overcommit ; there is a way to disable that.

Perhaps the mincore(2) , msync(2) , mlock(2) syscalls are interesting you.

Maybe you want the MAP_POPULATE or MAP_LOCKED flag of mmap(2)

I actually don't understand why you say "own the memory" in your question, which I don't understand very well. If you just want to disable memory overcommit, please tell.

And you might also mmap some file segment. I believe there is no possible overcommit in that case. But I would just suggest to disable memory overcommit in your entire system, thru /proc/sys/vm/overcommit_memory .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM