Reputation: 1843
we use "shm_open" to create a shared memory object, and then "mmap" to map it to a memory region. However, in later time, when the code actually accesses the memory, in some corner cases, it will hit "bus error" as the underlying physical memory was running out.
This seems to be a generic thing in Linux as the "mmap" only map the virtual memory address space and the system allocates the actual physical memory only when you access the pages.
My question is: how should I handle such "exception" gracefully? What are the best practices? I don't want the program crashes when the underlying memory runs out, I wanted to return ENOMEM in such case. Is there a way to achieve that?
Thanks.
Upvotes: 2
Views: 1720
Reputation: 2470
On Linux (with glibc) the implementation the shared memory objects shm_open creates are actual files in /dev/shm. Under normal circumstances there is a tmpfs mounted at that location with default options, i.e. its maximum size is half the physical memory. If that is not enough, instead of using shm_open you can create files to be mmap'ed elsewhere where there is more space available.
There is little you can do when you get such an exception. In particular you can't just return ENOMEM or something because the exception is caused by whatever write to the mmap'ed region that caused the failed allocation. That can be literally any write in your code to that area and there is no concept in programming languages of simple memory accesses failing, much less means to handle such a situation.
Upvotes: 1