Get the copy-on-write behaviour of fork()ing, without fork()

蓝咒 提交于 2019-12-18 04:11:02

问题


I have a large buffer:

char *buf = malloc(1000000000); // 1GB

If I forked a new process, it would have a buf which shared memory with the parent's buf until one or the other wrote to it. Even then, only one new 4KiB block would need to be allocated by the kernel, the rest would continue to be shared.

I'd like to make a copy of buf, but I'm only going to change a little of the copy. I'd like copy-on-write behaviour without forking. (Like you get for free when forking.)

Is this possible?


回答1:


You'll want to create a file on disk or a POSIX shared memory segment (shm_open) for the block. The first time, map it with MAP_SHARED. When you're ready to make a copy and switch to COW, call mmap again with MAP_FIXED and MAP_PRIVATE to map over top of your original map, and with MAP_PRIVATE to make the second copy. This should get you the effects you want.



来源:https://stackoverflow.com/questions/10998943/get-the-copy-on-write-behaviour-of-forking-without-fork

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!