当前位置:网站首页>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
边栏推荐
- 3DE 资源没东西或不对
- Fiori 应用通过 Adaptation Project 的增强方式分享
- Rust language - Introduction to Xiaobai 05
- [QT widget] encapsulates a simple thread management class
- cvpr2022 human pose estiamtion
- 【扫盲】机器学习图像处理中的深层/浅层、局部/全局特征
- 搜狗微信APP逆向(二)so层
- 旅游管理系统
- Fiori applications are shared through the enhancement of adaptation project
- Resttemplate remote call tool class
猜你喜欢

Object memory layout

Selection of all-optical technology in the park - Part 2

Single step debugging analysis of rxjs observable of operator

rxjs Observable of 操作符的单步调试分析

Fiori applications are shared through the enhancement of adaptation project

Congratulations on the release of friends' new book (send welfare)

447 Bili Bili noodles warp 1

el-input文本域字数限制,超过显示变红并禁止输入

【JetCache】JetCache的使用方法与步骤

MySQL5.7 设置密码策略(等保三级密码改造)
随机推荐
微信开放平台扫码登录[通俗易懂]
效率提升 - 鼓捣个性化容器开发环境
Configure filter
[C language] detailed explanation of malloc function [easy to understand]
Pytorch nn. functional. Simple understanding and usage of unfold()
使用 Three.js 实现'雪糕'地球,让地球也凉爽一夏
Selection of all-optical technology in the park - Part 2
MySQL数据库详细学习教程
Explain kubernetes network model in detail
LC501. Mode in binary search tree
Cut noodles C language
Slope compensation
SAP UI5 应用开发教程之一百零四 - SAP UI5 表格控件的支持复选(Multi-Select)以及如何用代码一次选中多个表格行项目
Little red book scheme jumps to the specified page
Single step debugging analysis of rxjs observable of operator
The second anniversary of the three winged bird: the wings are getting richer and the take-off is just around the corner
ECMAScript 2022 正式发布,有你了解过的吗?
Rust语言——小小白的入门学习05
配置筛选机
nn.Parameter】Pytorch特征融合自适应权重设置(可学习权重使用)