首页 > 解决方案 > 如何在centos上使用bash获取nodejs进程使用的总内存(以MB为单位)

问题描述

不知何故,使用 PM2 imonit,它可以显示 nodeJS 进程使用的 CPU 和内存。 我的ss

如何在 centos 上使用 bash 脚本获得相同的值(兆字节)?

这就是我所拥有的:

admin@cent7a ~/w/s/app> ps aux | grep -i node
admin    24722  0.3  2.0 2509600 74632 ?       Ssl  18:36   0:09 node /home/admin/www/survey/app/app.js
admin    24880  0.0  1.0 926516 39196 pts/0    Sl+  18:37   0:00 node /bin/pm2 logs
admin    26556  5.5 10.3 2786552 374500 ?      Sl   18:49   2:00 node /home/admin/www/survey/app/index.js
admin    27938  4.1 11.0 2870796 398924 ?      Sl   18:59   1:06 node /home/admin/www/survey/app/index.js
admin    32015  0.0  0.0 112812   988 pts/1    R+   19:26   0:00 grep --color=auto -i node

标签: node.jsbashmemorysh

解决方案


ps -o rss查看实际内存使用情况

使用-o选项 或--format,您可以指定一种用户定义的格式,让您可以查看进程的内存使用情况(占总内存的百分比)。rss此处用于显示内存使用情况。

命令分解

# without pid and command you'll just have memory which isn't useful
# does not work with -u or -v, you'll need to specify all format options yourself
ps -axo pid,rss,command

如果您不想指定格式的每个部分怎么办?

您还可以选择仅提供一个-v选项ps,它将显示实际内存使用情况以及其他相关统计信息以及默认列。

命令分解

# does not work with -u
ps -axv

如何将此值转换为兆字节?

您可以获取 from 提供的值ps -o rss并将其除以1024with bc。以下是此管道的示例。

echo "scale=2; $(ps -o rss <PID> | tail -1) / 1024" | bc -l

分解

# scale=2; is for `bc` to truncate the number of digits after the decimal point
echo "scale=2; $(

# Gets the real memory usage of your process
# (but still contains column headers line)
  ps -o rss <PID> |

# Remove the column headers by grabbing the last line
  tail -1

# Convert from Kilobytes to Megabytes
) / 1024" |

# Handle the math (-l allows it to do fractional division)
bc -l

推荐阅读