【问题标题】:How to get information about free memory from /dev/shm如何从 /dev/shm 获取有关可用内存的信息
【发布时间】:2013-08-18 12:42:24
【问题描述】:

我需要一种 C 或 C++ 方法来从 /dev/shm 获取可用内存。请注意,在我在 Linux 上的 ARM 架构上,不幸的是,ipcs 报告了错误的最大值。可用内存信息,但df -h 正确地给了我来自tmpfs 的当前可用内存。

问题是我试图通过 boost::interprocess::shared_memory_object::truncate 分配共享内存,但是当内存不可用时,这个函数不会抛出。这个问题显然不在boost::interprocess 中,而是来自底层ftruncate(),当没有可用内存时(https://svn.boost.org/trac/boost/ticket/4374)不会返回相应的错误,所以boost 不能抛出任何东西。

【问题讨论】:

    标签: c++ c boost boost-interprocess


    【解决方案1】:

    试试 statvfs glibc 函数,或者 statfs 系统调用

    #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    
    

    【讨论】:

      【解决方案2】:

      posix_fallocate() 将在文件系统中分配支持扩展区,或者如果空间不足 (ENOSPC) 则失败。

      #include <fcntl.h>
      
      int posix_fallocate(int fd, off_t offset, off_t len);
      

      posix_fallocate() 函数应确保在文件系统存储介质上分配从偏移量开始并持续 len 字节的常规文件数据所需的任何存储空间。如果 posix_fallocate() 返回成功,后续对指定文件数据的写入不会因为文件系统存储介质上的可用空间不足而失败。

      这听起来像是您可能想要的功能。

      【讨论】:

      • 我会尽力让你知道的。谢谢。
      猜你喜欢
      • 2017-08-26
      • 1970-01-01
      • 2019-07-07
      • 2012-09-14
      • 2013-04-08
      • 2021-06-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多