Linux中追蹤記憶體
- 2019.03.06
- Linux Shell Script
- 追蹤特定User的特定Process:
#!/bin/sh output_folder="./MemoryTracing" if [ ! -d $output_folder ] then mkdir $output_folder fi file="$output_folder/$(date '+%y%m%d').txt" rm $file while true do now=$(date '+%H:%M:%S.%3N') top=$(echo -n $(top -b -n 1 | grep -E '{User Name}.*{Process Name}')) if [ -n "$top" ] then echo "${now} ${top}" >> $file fi sleep 0.05 done
- 追蹤System全體的CPU和Memory消耗:
#!/bin/sh output_folder="./SystemTracing" if [ ! -d $output_folder ] then mkdir $output_folder fi file="$output_folder/$(date '+%y%m%d').txt" rm $file user_name="{User Name}" main_process="{Main Process Name}" other_processes=("{Other Process Name 1}" "{Other Process Name 1}" ...) filter="${user_name}.*${main_process}" main_filter=$filter for i in "${other_processes[@]}" do filter=${filter}"|${user_name}.*${i}" # 作為grep命令的PATTERNS - 「|」的左右不可有空格 done while true do now=$(date '+%H:%M:%S.%3N') top=$(echo -n $(top -b -n 1 | grep -E "${filter}")) if [ -n "$top" ] then pos=0 cpu=0; virt=0; res=0; while true do if [ ! -n "$(echo ${top} | cut -d' ' -f $(($pos+1)))" ] then break fi cpu_now=$(echo ${top} | cut -d' ' -f $(($pos+9))) cpu=$(awk 'BEGIN{printf "%.2f\n",('${cpu}'+'${cpu_now}')}') # 小數點運算加法: ans=$(awk 'BEGIN{printf "%.2f\n",('$a'+'$b')}') virt_now=$(echo ${top} | cut -d' ' -f $((${pos}+5))) virt=$((${virt}+${virt_now})) res_now=$(echo ${top} | cut -d' ' -f $((${pos}+6))) res=$((${res}+${res_now})) pos=$(($pos+12)) # 整數運算加法: ans=$(($a+$b)) done echo "${now} ${cpu} ${virt} ${res}" echo "${now} ${cpu} ${virt} ${res}" >> $file fi sleep 0.05 done
Last Updated on 2023/08/16 by A1go