6

linux-ubuntu 运行C语言等编写的程序时,如何查看程序占用的内存等资源信息

 3 years ago
source link: https://blog.popkx.com/linux-ubuntu-how-to-get-informations-when-run-c-programed-appications-and-so-on/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

linux-ubuntu 运行C语言等编写的程序时,如何查看程序占用的内存等资源信息

发表于 2018-07-04 20:07:13   |   已被 访问: 662 次   |   分类于:   Linux笔记   |   2 条评论

尤其是嵌入式开发,程序开发好之后,非常关心其运行在 linux 主机上到底占用多少资源。查看内存占用时,当然可以对比运行程序前后系统内存的变化,但是这样非常不准确,而且,如果程序本身非常小,可能根本对比不出信息。本节介绍如何获取程序运行占用的资源。

先写一个测试 demo


demo 代码如下:

#include <stdio.h>
#include <unistd.h>

int main()
{
    while(1){
        sleep(2);
        printf("test is running...\n");
    } 
    return 0;
} 

demo 非常简单,功能就是每隔两秒在终端打印

test is running...

编译之,在后台运行。

$ gcc -o test test.c 
$ ./test &          # 加 & 可以后台运行
[1] 44345
$ test is running...
test is running...
test is running...
test is running...
test is running...
...

44345 是 test 的 pid。

查看 demo 占用资源


linux 下查看某个进程占用的资源非常简单,只需要执行

cat /proc/44345/status

status
Name:   test
State:  S (sleeping)
Tgid:   44345
Ngid:   0
Pid:    44345
PPid:   2463
TracerPid:  0
Uid:    1000    1000    1000    1000
Gid:    1000    1000    1000    1000
FDSize: 256
Groups: 4 24 27 30 46 113 128 1000 
NStgid: 44345
NSpid:  44345
NSpgid: 44345
NSsid:  2463
VmPeak:     4352 kB
VmSize:     4352 kB
VmLck:         0 kB
VmPin:         0 kB
VmHWM:       652 kB
VmRSS:       652 kB
VmData:      184 kB
VmStk:       132 kB
VmExe:         4 kB
VmLib:      1944 kB
VmPTE:        32 kB
VmPMD:        12 kB
VmSwap:        0 kB
HugetlbPages:          0 kB
Threads:    1
SigQ:   0/7769
SigPnd: 0000000000000000
ShdPnd: 0000000000000000
SigBlk: 0000000000000000
SigIgn: 0000000000000000
SigCgt: 0000000000000000
CapInh: 0000000000000000
CapPrm: 0000000000000000
CapEff: 0000000000000000
CapBnd: 0000003fffffffff
CapAmb: 0000000000000000
Seccomp:    0

Speculation_Store_Bypass:   vulnerable
Cpus_allowed:   ffffffff,ffffffff,ffffffff,ffffffff
Cpus_allowed_list:  0-127
Mems_allowed:   00000000,00000001
Mems_allowed_list:  0
voluntary_ctxt_switches:    112
nonvoluntary_ctxt_switches: 4

各种信息都有了, 看到 VmSize: 4352 kB,才知道这么简单的程序也要占用这么多内存。

所以,只要知道程序的 pid 就可以查出它占用的资源。如果我们只知道程序名,而不知道它的 pid,怎么查呢?这里以 test 程序为例,只需执行

ps -A | grep test       # grep 后加要查的程序名

 44345 pts/2    00:00:00 test

发现 pid=44345,与前面是一致的。

如果想停止 test 程序,执行 kill 44345 即可

阅读更多:   Linux笔记


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK