当前位置:网站首页>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
边栏推荐
猜你喜欢

Rust语言——小小白的入门学习05

Explain kubernetes network model in detail

SAP intelligent robot process automation (IRPA) solution sharing

MySQL MHA high availability configuration and failover

104. SAP UI5 表格控件的支持复选(Multi-Select)以及如何用代码一次选中多个表格行项目

Fiori applications are shared through the enhancement of adaptation project

2020-ViT ICLR

元宇宙可能成为互联网发展的新方向

Single step debugging analysis of rxjs observable of operator

Today's sleep quality record 71 points
随机推荐
cvpr2022 human pose estiamtion
Understanding of inverted residuals
【扫盲】机器学习图像处理中的深层/浅层、局部/全局特征
Efficiency improvement - encourage personalized container development environment
QStringList 的常规使用
Learn MySQL from scratch - database and data table operations
Share some feelings of a programmer who has experienced layoffs twice a year
Mixconv code
[daily training] 326 Power of 3
Appium自动化测试基础 — 补充:Desired Capabilities参数介绍
MySQL stored procedure
[untitled]
Understanding of transactions in MySQL
H5 model trained by keras to tflite
台积电全球员工薪酬中位数约46万,CEO约899万;苹果上调日本的 iPhone 售价 ;Vim 9.0 发布|极客头条
redis配置文件中常用配置详解[通俗易懂]
447 Bili Bili noodles warp 1
转--拿来即用:分享一个检查内存泄漏的小工具
Ffmpeg learning notes
Clean up system cache and free memory under Linux