【问题标题】:How to show which users are running which processes and how much memory they take?如何显示哪些用户正在运行哪些进程以及他们占用了多少内存?
【发布时间】:2023-02-10 22:27:08
【问题描述】:

每个人。

我目前正在用 Bash 创建一个小脚本。

我正在尝试创建一个程序,该程序将显示每次使用的所有正在运行的进程以及每个进程占用的内存量。我知道我需要使用 ps aux 命令。

基本上我希望输出看起来像这样

USER     PROCESS    MEMORY
ROOT     Process1      10KB
         Process2     120KB
USER1    Process 1    50KB
         Process 4     1 KB

这是我现在的代码,我不知道如何进一步发展

#!/bin/bash

runningUsers=$( ps aux | awk '{ print $1 }' | sed '1 d' | sort | uniq | perl -e 'for (<>) { chomp; $u = ( getpwnam($_) )[2]; print $_, "\n" if ( ( $u >= 1000 || $u == 0 ) && ( $_ =~ /[[:alpha:]]/ && $_ ne "nobody" ) ) }')
echo $runningUsers

users=($runningUsers)

echo "${users[0]}"

【问题讨论】:

    标签: linux bash shell process


    【解决方案1】:

    Pfoef,你自己真的很难过。
    为什么不坚持已经提供您所需要的基础知识。

    #!/bin/bash
    ps -eo user,pid,%mem,comm --sort=-%mem | awk '
    BEGIN {
      printf "%-10s %-20s %-10s
    ", "USER", "PROCESS", "MEMORY"
    }
    {
      printf "%-10s %-20s %-10s
    ", $1, $4, sprintf("%.2f KB", $3*1024)
    }'
    

    printf %10 是宽度。

    该脚本提供:

    root@vm-local-1:~# ./test.sh
    USER       PROCESS              MEMORY
    USER       COMMAND              0.00 KB
    root       unattended-upgr      512.00 KB
    root       networkd-dispat      409.60 KB
    root       multipathd           409.60 KB
    root       systemd-journal      409.60 KB
    systemd+   systemd-resolve      307.20 KB
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-26
      • 1970-01-01
      相关资源
      最近更新 更多