2

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.

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
user1783732
  • 1,599
  • 5
  • 22
  • 44

1 Answers1

1

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.

Andreas Bombe
  • 2,450
  • 13
  • 20
  • understood. However, is there any API in Linux that I can test such "exception", something like: "try_read(ptr)" so that the API will not cause SIGBUS if the physical page was not available and just returns an error code? The reason I am asking is that, in my program, there is a single piece of code that accesses this memory. Such API will be very useful if existed. – user1783732 Oct 16 '13 at 04:38