当前位置:网站首页>Turn -- bring it and use it: share a gadget for checking memory leaks
Turn -- bring it and use it: share a gadget for checking memory leaks
2022-07-01 22:51:00 【worthsen】
【 Original statement 】
If you think the article is good , Please forward 、 Share with your friends
I will summarize the practical experience of more than ten years of embedded development projects 、 Share , I believe it won't let you down !
Reprint : Welcome to reprint , But without the author's consent , This statement must be retained , The original link must be given in the article .
<article class="baidu_pl">
<div id="article_content" class="article_content clearfix">
<link rel="stylesheet" href="https://csdnimg.cn/release/blogv2/dist/mdeditor/css/editerView/ck_htmledit_views-163de54645.css">
<div id="content_views" class="htmledit_views">
<p><span style="color:#ffbb66;"><strong>【 Function description 】</strong></span></p>
【 Function description 】
stay The embedded During the development of system application , Memory leakage is a serious and troublesome problem . Yes, of course , There are many professional tools and software to check memory leaks , What I use more is memwatch, valgrind.
These tools are mainly used to check memory leaks in the development process . however , If all the programs are developed , Start Integration testing when , It is still found that system resources continue to decrease , So how to deal with it ?
The gadgets provided here are used to deal with this situation : Can monitor what you suspect 、 System resources used by those processes that may have memory leaks .
Especially when a system is developed by more than one person 、 A situation consisting of multiple processes , If there is a resource leak , Who should you suspect first ? Who should check whether there is a problem with their own program first ? Wrangling often happens , The estrangement between small partners has also planted seeds in the subconscious .
here , The data output from the monitoring program is the most useful !
【 Test environment 】
1. x86 System
I was in Ubuntu16.04 Under test , Use the system gcc compiler .
2. Embedded system
Just replace the compiler with the corresponding cross compiler .
【 The code download 】
1. Network disk
https://pan.baidu.com/s/1yNrjQ6var8xokAJWEsFYFw
passwd:uqbh
/**
* @brief: This gadget is used to monitor the resource usage of some processes in the system ,
* It can be used to check whether there is memory leak in the program .
*
* @author: WeChat captain5780
* @email: [email protected]
*
* @note: ./memory_trace < Process name 1> < Process name 2> < Process name 3>
*/
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define TRACE_ITEM_NUM 4
#define PROCESS_MAX 20
#define PROCESS_NAME_LEN 128
#define BUF_LEN 512
// Name of the resource to be monitored
char *TraceItem[TRACE_ITEM_NUM] =
{"VmSize", "VmRSS", "VmStk", "VmData"};
// Save the name of the process to be monitored
char *ProcessList[PROCESS_MAX];
// Print a message , It can be used in actual projects zlog Wait for logging tools to record to the file system .
static void log_msg(const char *msg)
{
printf("%s", msg);
}
int main(int argc, char *argv[])
{
// Check the maximum number of monitored processes
if (argc >= PROCESS_MAX) {
printf("too many process \n");
exit(-1);
}
// Extract the process name passed in by the command line parameters , Save in ProcessList in .
int i, k, count;
for (i = 0, count = 0; i < argc - 1; i++) {
count++;
ProcessList[i] = (char *)malloc(PROCESS_NAME_LEN);
memset(ProcessList[i], 0, PROCESS_NAME_LEN);
sprintf(ProcessList[i], "%s", argv[i + 1]);
}
time_t rawtime;
struct tm *timeinfo;
char *buf = (char *)malloc(BUF_LEN);
while (1) {
// Record the current time
time(&rawtime);
timeinfo = localtime(&rawtime);
memset(buf, 0, BUF_LEN);
sprintf(buf, "\n[%02d:%02d:%02d] \n",
timeinfo->tm_hour,
timeinfo->tm_min,
timeinfo->tm_sec);
log_msg(buf);
// this for The loop is used to obtain the resource usage of the monitoring process
for (i = 0; i < count; i++) {
memset(buf, 0, BUF_LEN);
sprintf(buf, "[%s] \n", ProcessList[i]);
log_msg(buf);
for (k = 0; k < TRACE_ITEM_NUM; k++) {
memset(buf, 0, BUF_LEN);
// Acquisition process ID Number : Execute system commands , Then read the output .
sprintf(buf,
"ps -aux | grep %s | grep -v grep | awk '{print $2}'",
ProcessList[i]);
FILE *fp = popen(buf, "r");
if (NULL == fp) {
printf("popen failed! \n");
continue;
}
char line[128] = { 0 };
fgets(line, 128, fp);
int len = strlen(line);
if (*(line + len - 1) == '\n')
*(line + len - 1) = 0;
pclose(fp);
// According to the process ID Number , Get the stack information of the process .
memset(buf, 0, BUF_LEN);
sprintf(buf,
"cat /proc/%s/status | grep %s | grep -v grep",
line, TraceItem[k]);
fp = popen(buf, "r");
if (NULL == fp) {
printf("popen failed! \n");
continue;
}
fgets(line, 128, fp);
pclose(fp);
log_msg(line); // Record it in the Journal
}
}
// Get the idle resource information of the system
memset(buf, 0, BUF_LEN);
sprintf(buf, "free | grep Mem: | grep -v grep");
FILE *fp = popen(buf, "r");
if (NULL == fp) {
printf("popen failed! \n");
continue;
}
char line[128] = { 0 };
fgets(line, 128, fp);
pclose(fp);
log_msg(line);
sleep(5); // At intervals
}
// Release malloc Allocated heap space
free(buf);
for (i = 0; i < PROCESS_MAX; i++) {
if (ProcessList[i])
free(ProcessList[i]);
}
return 0;
}
3. Printout
The function of this tool is actually very simple , It is to call system instructions to monitor the system resources occupied by processes .
Specifically, continuous output :/proc/[pid]/status The content of . This document contains 4 Key indicators , Here is a brief list of , The specific meaning can be searched .
VmSize(KB): The size of virtual memory used by the process .
VmRSS(KB): Part of the process that resides in physical memory , Not swapped to hard disk .
VmStk(KB): The size of the stack used by the process .
VmData(KB): The size of the process data segment .
【 Why write this gadget 】
I wrote an Internet of things gateway product before , These include 3 It's a big module , And it is the responsibility of different people , What is fatal is : this 3 I'm alone in Japan , One in Taiwan , And then there's us .
During the integration test, it is found that the system resources continue to decrease , And there is no rule . Because there are many interactions between processes , Maybe it's just when some specific execution logic is triggered , Memory leakage and other situations may occur .
In order to find out the culprit , So I wrote this gadget . About 2 Time of day , It soon located the source of the problem .
【 Problems you may encounter 】
1. System instructions
Several system instructions are used in the program :proc, grep, awk, free.
The output format of these instructions may be different in different embedded systems , If there is a problem with the output of running this tool directly , Then you need to adjust the instruction parsing part of the code .
2. How to adjust
for example : This instruction is used in the code according to Process name obtain process ID:ps -aux | grep %s | grep -v grep | awk '{print $2}’
about ps Instructions , It may not be necessary in your system -aux attribute .
about awk Instructions , The self-contained information extracted in your system may be '{print $1}’.
True knowledge comes from practice !
【END】
1. This is an original article , Please respect the copyright . If you want to reprint , Please keep all contents and indicate the source . If it's convenient , Please contact me to confirm .
2. If there are mistakes in the article , Or hope to communicate 、 Discuss relevant contents , Welcome to contact me .
3. mailbox :[email protected]
4. official account :IOT Internet of things town
边栏推荐
- 园区全光技术选型-中篇
- Understanding of indexes in MySQL
- nn.Parameter】Pytorch特征融合自适应权重设置(可学习权重使用)
- Using securecrtportable to remotely connect virtual machines
- vSphere+、vSAN+来了!VMware 混合云聚焦:原生、快速迁移、混合负载
- Multi picture alert ~ comparison of Huawei ECs and Alibaba cloud ECS
- MySQL中对于事务的理解
- The fixed assets management subsystem reports are divided into what categories and which accounts are included
- Pytorch nn.functional.unfold()的简单理解与用法
- [C language] detailed explanation of malloc function [easy to understand]
猜你喜欢
The fixed assets management subsystem reports are divided into what categories and which accounts are included
Yolov5.5 call local camera
Ida dynamic debugging apk
转--拿来即用:分享一个检查内存泄漏的小工具
Slope compensation
Sogou wechat app reverse (II) so layer
map容器
Kubernetes创建Service访问Pod
转--原来gdb的底层调试原理这么简单
MySQL5.7 设置密码策略(等保三级密码改造)
随机推荐
LC501. 二叉搜索树中的众数
使用 EMQX Cloud 实现物联网设备一机一密验证
微信开放平台扫码登录[通俗易懂]
利用SecureCRTPortable远程连接虚拟机
MySQL MHA high availability configuration and failover
2020-ViT ICLR
Clean up system cache and free memory under Linux
旅游管理系统
Yolov5.5 call local camera
友善串口助手使用教程_友善串口调试助手怎么进行配置-友善串口调试助手使用教程…
Rust language - Introduction to Xiaobai 05
陈天奇的机器学习编译课(免费)
3DE resources have nothing or nothing wrong
Ffmpeg learning notes
【无标题】
General use of qstringlist
cvpr2022 human pose estiamtion
[literacy] deep / shallow, local / global features in machine learning image processing
vSphere+、vSAN+来了!VMware 混合云聚焦:原生、快速迁移、混合负载
Selection of all-optical technology in the park - Part 2