0

Find and log which top 5 processes are taking high cpu

เวลาคอมพิวเตอร์ตระกูล *nix พบปัญหา อันดับแรก ๆ ที่จะเริ่มทำเพื่อแก้ปัญหาและช่วยชีวิตเราก็คือเปิด Log เกิดปัญหาปุ๊บเปิด Log ก่อนเลยแต่บางกรณีเราก็มอนิเตอร์ผ่านโปรแกรม/คำสั่งตัวอื่น โดยทั่ว ๆ ไปมักจะใช้ top เพื่อมอนิเตอร์การทำงานของคอมพิวเตอร์ ซึงโปรแกรมจะแสดงสถานะของ Memory, CPU, Process Terminal_042

top นี่คือต้องมีเวลานั่งดูเพราะผลลัพธ์ที่ได้จะแสดงออกมาแบบเรียลไทม์ อีกทางเลือกหนึ่งก็คือใช้คำสั่ง ps

ps – report a snapshot of the current processes.

 a@b  ~  ps -aux                                    1 ↵  481  11:31:05 
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root         1  0.0  0.0 185556  6264 ?        Ss   09:55   0:02 /sbin/init spla
root         2  0.0  0.0      0     0 ?        S    09:55   0:00 [kthreadd]
root         3  0.0  0.0      0     0 ?        S    09:55   0:00 [ksoftirqd/0]
root         5  0.0  0.0      0     0 ?        S<   09:55   0:00 [kworker/0:0H]
root         7  0.0  0.0      0     0 ?        S    09:55   0:05 [rcu_sched]
root         8  0.0  0.0      0     0 ?        S    09:55   0:00 [rcu_bh]
root         9  0.0  0.0      0     0 ?        S    09:55   0:00 [migration/0]
root        10  0.0  0.0      0     0 ?        S    09:55   0:00 [watchdog/0]
root        11  0.0  0.0      0     0 ?        S    09:55   0:00 [watchdog/1]

ps ใช้แล้วก็จบไง จะดูอีกก็สั่งอีก (ใช้ watch ดูแบบ top ก็ได้นะ แต่จะใช้ watch ก็ไปใช้ top ละเอียดกว่าเยอะ) แต่ในกรณีที่ต้องการเก็บ Log ผลลัพธ์ที่ได้จาก ps เพื่อดูการทำงาน เช่นอาจจะต้องการมอนิเตอร์โปรเสสที่ใช้งานสูง ๆ หรือมอนิเตอร์ดูภายหลังว่าใครกำลังแอบแดกเมมมหาโหด ก็ทำแบบนี้ได้

while true; do 
    ps auxf | sort -nrk 3,3 | head -n 5 >> log.log; 
    sleep 1; 
done

ผลลัพธ์ที่ได้

a@b  ~  tail -f log.log                              ✓  488  11:40:13 
a        6019 28.6  4.0 2189732 663568 tty2   Sl+  09:57  28:48 /usr/lib/firefox/firefox
a        4376  4.7  1.2 2334564 198912 tty2   Sl+  09:57   4:49              \_ /usr/bin/gnome-shell
root      4222  2.7  0.4 534160 79804 tty2     Sl+  09:57   2:43          \_ /usr/lib/xorg/Xorg vt2 -displayfd 3 -auth /run/user/1000/gdm/Xauthority -background none -noreset -keeptty -verbose 3