当我执行没有任何标志的“top”命令时,我得到了
当我使用设置为每分钟运行的cronjob将其打印到文件时,执行下面的命令,但是,我只使用超过0.1%的内存和CPU来获得两个或三个进程。
cronjob执行此命令:
top -b -n 1 | sed -n '8,17p' | sed 's/^ *//' | tr -s ' ' | sed 's/ /", "/g ; s/^/{"/g ; s/$/"},/g ; 1s/^/[/ ; $ s/.$/]/ ; s/"/"pid": "/1 ; s/"/"user": "/5 ; s/"/"pr": "/9 ; s/"/"ni": "/13 ; s/"/"virt": "/17 ; s/"/"res": "/21 ; s/"/"shr": "/25 ; s/"/"s": "/29 ; s/"/"cpu": "/33 ; s/"/"mem": "/37 ; s/"/"time": "/41 ; s/"/"command": "/45 ; s/"\(-\?[0-9]\+\)"/\1/g'
以批处理模式获取“top”的第一帧并以JSON格式返回,例如像这样的东西:
[
{
"pid": 7303,
"user": "fahclie+",
"pr": 39,
"ni": 19,
"virt": 255736,
"res": 14716,
"shr": 5556,
"s": "S",
"cpu": "400,9",
"mem": "0,2",
"time": "210:15.98",
"command": "FahCore_a4"
},
{
"pid": 1,
"user": "root",
"pr": 20,
"ni": 0,
"virt": 42040,
"res": 4664,
"shr": 2840,
"s": "S",
"cpu": "0,0",
"mem": "0,1",
"time": "0:01.16",
"command": "init"
},
{
"pid": 2,
"user": "root",
"pr": 20,
"ni": 0,
"virt": 0,
"res": 0,
"shr": 0,
"s": "S",
"cpu": "0,0",
"mem": "0,0",
"time": "0:00.00",
"command": "kthreadd"
},
{
"pid": 3,
"user": "root",
"pr": 20,
"ni": 0,
"virt": 0,
"res": 0,
"shr": 0,
"s": "S",
"cpu": "0,0",
"mem": "0,0",
"time": "0:00.13",
"command": "ksoftirqd/0"
},
{
"pid": 5,
"user": "root",
"pr": 0,
"ni": -20,
"virt": 0,
"res": 0,
"shr": 0,
"s": "S",
"cpu": "0,0",
"mem": "0,0",
"time": "0:00.00",
"command": "kworker/0:+"
},
{
"pid": 7,
"user": "root",
"pr": 20,
"ni": 0,
"virt": 0,
"res": 0,
"shr": 0,
"s": "S",
"cpu": "0,0",
"mem": "0,0",
"time": "0:03.58",
"command": "rcu_sched"
},
{
"pid": 8,
"user": "root",
"pr": 20,
"ni": 0,
"virt": 0,
"res": 0,
"shr": 0,
"s": "S",
"cpu": "0,0",
"mem": "0,0",
"time": "0:00.00",
"command": "rcu_bh"
},
{
"pid": 9,
"user": "root",
"pr": 20,
"ni": 0,
"virt": 0,
"res": 0,
"shr": 0,
"s": "S",
"cpu": "0,0",
"mem": "0,0",
"time": "0:01.26",
"command": "rcuos/0"
},
{
"pid": 10,
"user": "root",
"pr": 20,
"ni": 0,
"virt": 0,
"res": 0,
"shr": 0,
"s": "S",
"cpu": "0,0",
"mem": "0,0",
"time": "0:00.00",
"command": "rcuob/0"
},
{
"pid": 11,
"user": "root",
"pr": "rt",
"ni": 0,
"virt": 0,
"res": 0,
"shr": 0,
"s": "S",
"cpu": "0,0",
"mem": "0,0",
"time": "0:00.51",
"command": "migration/0"
}
]
请注意,从第三个进程开始,这些进程中没有一个使用超过0.0%的内存或CPU。
我怀疑这是因为top的第一帧是正在写的那一帧,而在第一帧中,top仍在收集过程信息。
有没有办法将第二帧打印到文件中?
答案 0 :(得分:0)
我在freenode的#bash IRC频道中找到了答案,感谢jamesd:
首先我们使用top -b -n 2
返回前2帧。
然后我们将这些帧管道传输到grep -A10 'PID USER'
(10
是匹配行之后的尾随上下文行数,'PID USER'
标题行的开头),然后管道这样做的结果是tail -n 10
摆脱标题行。
这仅显示top
的第二帧的前10个进程。
10
当然可以替换为所需的进程数量,'PID USER'
可以替换个人top
配置标题行中的第一个字段。