JZsdk_monitor.c
2.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
#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;
}