C++ 获取Linux的可用内存

long get_memory_free()
{
    FILE*file=fopen("/proc/meminfo","r");
    if(file == nullptr){
        fprintf(stderr,"cannot open /proc/meminfo\n");
        return -1;
    }
    char str1[20];
    char str2[20];
    char str3[20];
    long mem_total      =0;
    long mem_available  =0;
    long mem_free       =0;
    fscanf(file, "MemTotal: %s kB\n", str1);
    mem_total = atol(str1) / 1000;
    fscanf(file,"MemAvailable: %s kB\n",str2);
    mem_available = atol(str2) / 1000;
    fscanf(file, "MemFree: %s kB\n", str3);
    mem_free = atol(str3) / 1000;
    fclose(file);
    fprintf(stderr, "Memory total: %ld MB\tMemory available: %ld MB\tMemory free: %ld MB\n", mem_total, mem_available, mem_free);
    return mem_free;
}

参考资料:

https://www.cnblogs.com/aimhabo/p/10776456.html

你可能感兴趣的:(C++,Linux,内存)