I want to allocate and initialise a fairly large chunk of contiguous memory (~1GB), then mark it as read-only and fork multiple (say several dozen) child processes which will use it, without making their own copies of the memory (the machine won't have enough memory for this).
Am I right in thinking that if I malloc
the memory as usual, then mark it as read-only with mprotect(addr, size, PROT_READ)
and then fork
, this will allow the child processes to safely use the memory without causing it to be copied? (Providing I ensure nothing tries to write to the allocated memory after the mprotect
call).
edit: Thanks for all the answers.
A followup question - I was planning on using shmget
, but I thought it used mm
and thus would be limited to smaller allocations (see the Restrictions section of this page). eg /proc/sys/kernel/shmmax
is 32MB on the server I'm using this one. But I want 1GB of contiguous memory. Am I wrong about this limitation?