linux下C程序查看内存剩余大小

嵌入式linux中很多内存资源都比较小,所以很多程序中在malloc时就需要提前知道内存剩余的大小

下面是一种调用 sysinfo接口来实现。

示例代码如下:

cpp 复制代码
#include <stdio.h>
#include <linux/kernel.h>
#include <linux/unistd.h>
#include <sys/sysinfo.h>
 
int main(void)
{
    struct sysinfo s_info;
    int error = sysinfo(&s_info);
    printf("error0: %d, total: %lu free: %lu \n", error, s_info.totalram, s_info.freeram);
    //func_call1(pcModelName);
 
    error = sysinfo(&s_info);
    printf("error1: %d, total: %lu free: %lu \n", error, s_info.totalram, s_info.freeram);
 
    int msg[500];
    int i = 0;
    for(i = 0; i < 1; i++)
    {
        //func_call2(pcSrcFile, msg);
        error = sysinfo(&s_info);
        printf("error2: %d, total: %lu free: %lu \n", error, s_info.totalram, s_info.freeram);
 
        //func_call3(pcSrcFile, msg);
        error = sysinfo(&s_info);
        printf("error3: %d, total: %lu free: %lu \n", error, s_info.totalram, s_info.freeram);
    }
 
    //func_call4();
    error = sysinfo(&s_info);
    printf("error4: %d, total: %lu free: %lu \n", error, s_info.totalram, s_info.freeram);
}
相关推荐
Rudon滨海渔村7 分钟前
Linux通用一键换源脚本.sh - ubuntu、centos全自动更换国内源 - LinuxMirrors神器
linux·运维·ubuntu·centos·换源
小琪琪:)9 分钟前
【Linux】vim配置----超详细
linux·运维·vim
江沉晚呤时1 小时前
在 Linux 上部署 .NET Core 应用并配置为开机自动启动
linux·服务器·mysql
NEWEVA__zzera221 小时前
CH585单片机的LCD外设怎么驱动段式LCD
c语言·单片机
长流小哥1 小时前
Linux网络编程 多进程UDP聊天室:共享内存与多进程间通信实战解析
linux·udp
郝亚军1 小时前
后向动态链表增删查改
linux·windows·链表
像素之间1 小时前
ts中的类型
linux·运维·ubuntu·typescript
may_一一1 小时前
(一)mac中Grafana监控Linux上的CPU等(Node_exporter 安装使用)
linux·服务器
羑悻的小杀马特2 小时前
【Linux篇章】进程通信黑科技:匿名管道的暗码传递与命名管道的实名使命
linux·运维·科技·匿名管道·命名管道
唯梦闲君3 小时前
ubuntu 22.04 安装和配置 mysql 8.0,设置开机启动
linux·数据库·mysql·ubuntu