Search code examples
c++cboostboost-interprocess

How to get information about free memory from /dev/shm


I need a way in C or C++ to get the free memory available from /dev/shm . Note that on my ARM architecure on Linux, unfortunately, ipcs reports a wrong max. available memory information, but df -h correctly gives me the current available memory from tmpfs.

The problem is that I am trying to allocate shared memory via boost::interprocess::shared_memory_object::truncate , but this function does not throw when the memory is not available. This problem is not apparently in boost::interprocess, but comes from the underlying ftruncate() which does not return the appropriate error when there is no memory available ( https://svn.boost.org/trac/boost/ticket/4374 ), so boost cannot throw anything.


Solution

  • Try the statvfs glibc function, or the statfs system call

    #include <sys/statvfs.h>
    int statvfs(const char *path, struct statvfs *buf);
    
    #include <sys/vfs.h>    /* or <sys/statfs.h> */
    int statfs(const char *path, struct statfs *buf);
    
    // in both structures you can get the free memory
    // by the following formula.
    free_Bytes = s->f_bsize * s->f_bfree