Question

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.

Was it helpful?

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    

OTHER TIPS

posix_fallocate() will either allocate the backing extents in the filesystem, or fail if there's insufficient space (ENOSPC).

#include <fcntl.h>

int posix_fallocate(int fd, off_t offset, off_t len);

The posix_fallocate() function shall ensure that any required storage for regular file data starting at offset and continuing for len bytes is allocated on the file system storage media. If posix_fallocate() returns successfully, subsequent writes to the specified file data shall not fail due to the lack of free space on the file system storage media.

This sounds like the feature that you may want instead.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top