无法使用进程 ID 获取 cpu 和内存使用情况

Unable to get the cpu and memory usage using process id

我正在尝试获取 PID 中的进程 ID,然后使用 grep 命令列出的所有进程 ID 获取 cpu 和内存使用情况,但我遇到了错误。任何帮助将不胜感激

#!/bin/bash
PID=`ps -eaf | grep firefox | grep -v grep | awk '{print }'`
usage= `ps -p $PID -o %cpu,%mem`

错误:

error: process ID list syntax error

Usage:
 ps [options]

 Try 'ps --help <simple|list|output|threads|misc|all>'
  or 'ps --help <s|l|o|t|m|a>'
 for additional help text.

For more details see ps(1).

当 firefox 不是 运行 时通常会发生这种情况:PID 不存在并且您会出现以下行为:

Prompt>ps -p -o %cpu,%mem // as firefox does not run, $PID is empty
error: process ID list syntax error

Usage:
 ps [options]

 Try 'ps --help <simple|list|output|threads|misc|all>'
  or 'ps --help <s|l|o|t|m|a>'
 for additional help text.

For more details see ps(1).

一次做一个

#!/bin/bash
for PID in `ps -eaf | grep firefox | grep -v grep | awk '{print }'` ; do
    usage=`ps -p $PID -o %cpu,%mem`
done

获取 pid csv 列表的建议命令 pgrep -d, -f firefox .

或将pids_list收集到变量中:

pid_list=$(pgrep -d, -f firefox)

现在使用ps命令提取关于$pid_list

的信息
ps -p $pid_list -o %cpu,%mem

或一行:

ps -p $(pgrep -d, -f firefox) %cpu,%mem