JZsdk_monitor.c 2.5 KB
#include "JZsdkLib.h"
#include "./JZsdk_monitor.h"
#include <pthread.h>

static long long get_total_ram() 
{  
    FILE *file;  
    char line[128];  
    long long total_ram = 0;  
  
    file = fopen("/proc/meminfo", "r");  
    if (!file) {  
        perror("Error opening /proc/meminfo");  
        return 0;
    }  
  
    while (fgets(line, sizeof(line), file)) {  
        if (strncmp(line, "MemTotal:", 9) == 0) {  
            sscanf(line, "MemTotal: %lld kB", &total_ram);  
            break;  
        }  
    }  
  
    fclose(file);  
    return total_ram;  
}  
  
static long long get_current_rss(pid_t pid) 
{  
    FILE *file;  
    char line[128];  
    long long vmrss = 0;  
  
    char path[64];  
    snprintf(path, sizeof(path), "/proc/%d/status", pid);  
  
    file = fopen(path, "r");  
    if (!file) {  
        perror("Error opening /proc/[pid]/status");  
        return 0;  
    }  
  
    while (fgets(line, sizeof(line), file)) {  
        if (strncmp(line, "VmRSS:", 6) == 0) {  
            sscanf(line, "VmRSS: %lld kB", &vmrss);  
            break;  
        }  
    }  
  
    fclose(file);  
    return vmrss;  
}

static void *MonitorTask(void *arg)
{
    //获取程序的pid号
    pid_t pid = getpid(); // 获取当前进程的 PID  
    long long total_ram;            //最大ram内存
    long long current_rss;          //RSS内存
    double memory_percentage;       //内存百分比
    
    // 获取系统总 RAM  
    total_ram = get_total_ram();  

    while (1)
    {
        printf("当前进程pid号%d\n",pid);

        // 获取当前进程的内存使用量  
        current_rss = get_current_rss(pid);  
  
        // 计算内存百分比  
        if (total_ram > 0) 
        {  
            memory_percentage = (double)current_rss / total_ram * 100;  
        } else {  
            memory_percentage = 0;  
        }  
  
        // 打印结果  
        printf("Program current memory usage: %lld KB\n", current_rss);  
        JZSDK_LOG_INFO("Monitor:(%.2f%% of total RAM)", memory_percentage);

        delayS(10);
    }
}



T_JZsdkReturnCode JZsdk_Log_Monitor_Init()
{
    pthread_t work_mode_task;
	pthread_attr_t task_attribute; //线程属性
	pthread_attr_init(&task_attribute);  //初始化线程属性
	pthread_attr_setdetachstate(&task_attribute, PTHREAD_CREATE_DETACHED);      //设置线程属性
	int timer = pthread_create(&work_mode_task,&task_attribute,MonitorTask,NULL);		//线程
    if(timer != 0)
    {
        printf("创建计时线程失败!\n");
    }

    return JZ_ERROR_SYSTEM_MODULE_CODE_SUCCESS;
}