当前位置:网站首页>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
边栏推荐
- 数字货币:影响深远的创新
- 微信开放平台扫码登录[通俗易懂]
- 陈天奇的机器学习编译课(免费)
- Selection of all-optical technology in the park - Part 2
- 倒置残差的理解
- Dark horse programmer - software testing - stage 06 2-linux and database-01-08 Chapter 1 - description of the content of the Linux operating system stage, description of the basic format and common fo
- 效率提升 - 鼓捣个性化容器开发环境
- How to write a performance test plan
- MySQL stored procedure
- [C language] detailed explanation of malloc function [easy to understand]
猜你喜欢
Mysql5.7 set password policy (etc. three-level password transformation)
Fiori applications are shared through the enhancement of adaptation project
SAP 智能机器人流程自动化(iRPA)解决方案分享
MySQL中对于事务的理解
Slope compensation
使用 EMQX Cloud 实现物联网设备一机一密验证
Cut noodles C language
Congratulations on the release of friends' new book (send welfare)
447 Bili Bili noodles warp 1
Yolov5.5 call local camera
随机推荐
Fully annotated SSM framework construction
Rust language - Introduction to Xiaobai 05
数字货币:影响深远的创新
internal field separator
业务可视化-让你的流程图'Run'起来
Operation category read is not supported in state standby
下班前几分钟,我弄清了v-model与.sync的区别
删除AWS绑定的信用卡账户
Fiori applications are shared through the enhancement of adaptation project
20220701
FFMpeg学习笔记
台积电全球员工薪酬中位数约46万,CEO约899万;苹果上调日本的 iPhone 售价 ;Vim 9.0 发布|极客头条
3DE resources have nothing or nothing wrong
Rust语言——小小白的入门学习05
Arlo's thinking after confusion
3DE 资源没东西或不对
There is no signal in HDMI in computer games caused by memory, so it crashes
微信开放平台扫码登录[通俗易懂]
SAP UI5 应用开发教程之一百零四 - SAP UI5 表格控件的支持复选(Multi-Select)以及如何用代码一次选中多个表格行项目
General use of qstringlist