系统负载与多任务环境下的监控需求
在现代操作系统中,Linux 作为典型的多用户、多任务系统,允许多个用户通过本地或远程方式同时登录并运行大量程序。这种高并发能力带来了高效性,但也引入了资源竞争和系统过载的风险。当系统响应变慢甚至卡顿时,管理员必须快速定位问题根源------是哪个用户?哪个进程?消耗了多少 CPU 或内存?
为此,Linux 提供了一系列强大的命令行工具用于实时监控系统活动。本文将围绕 w
、ps
和 top
三大核心命令展开详尽分析,结合技术细节、输出解读以及 NestJS + TypeScript 的实际代码模拟场景,帮助你构建完整的系统监控知识体系。
w
命令:全面掌握当前登录用户及其行为
1 ) 功能概述
w
命令(全称:who + what)用于显示当前登录系统的用户列表,并展示他们在执行什么任务、已空闲多久、CPU 使用情况等关键信息
该命令输出分为两部分:
- 第一行:系统摘要信息(时间、运行时长、登录用户数、负载平均值)
- 后续行:每个终端会话的详细信息
2 ) 输出结构解析
bash
$ w
07:26:44 up 24 min, 2 users, load average: 0.77, 0.26, 0.12
USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT
oscarl :0 :0 07:02 ?xdm? 38:12 0.00s /usr/lib/gnome-session-binary --session gnome-classic
oscarl pts/0 :0 07:17 3.00s 0.22s 0.06s w
第一行字段解释:
字段 | 含义 |
---|---|
07:26:44 |
当前系统时间 |
up 24 min |
系统已连续运行 24 分钟(即 uptime) |
2 users |
当前有 2 个用户会话正在连接 |
load average: 0.77, 0.26, 0.12 |
过去 1分钟、5分钟、15分钟内的平均负载 |
- 当前时间:如
07:26:44
,表示命令执行时刻。 - 系统运行时间(uptime):紧随其后的
up 24 minutes
表示自上次启动以来已连续运行 24 分钟。该值可通过独立命令uptime
获取,二者输出一致。 - 登录用户数:显示
2 users
,即当前有两位用户会话处于活跃状态。 - 负载平均值(Load Average):三个数值分别代表过去 1分钟、5分钟、15分钟内系统的平均活跃进程数,例如
0.77, 0.26, 0.12
重点说明:负载均值(Load Average)
- 表示单位时间内处于可运行状态或不可中断睡眠状态的平均进程数。
- 单核 CPU 负载 > 1 表示过载;四核 CPU 负载 > 4 才为过载。
- 若长期高于 CPU 核心数,则表明系统存在性能瓶颈。
可通过 uptime
命令单独获取此信息:
bash
$ uptime
07:28:46 up 26 min, 2 users, load average: 0.68, 0.30, 0.14
为了更直观地观察负载变化趋势,可使用 tload
命令绘制 ASCII 负载曲线图:
bash
$ tload
此命令以图形化方式展示负载随时间的变化,横轴为时间,纵轴为负载值,适合终端环境下进行初步性能诊断
用户活动列表:终端、IP、空闲时间与进程消耗
后续各行展示每个登录会话的详细信息,共八列:
列名 | 含义说明 |
---|---|
USER | 登录用户名(如 oscar ) |
TTY | 终端设备名: - :0 表示图形界面本地终端(对应 tty1 ) - pts/0 , pts/1 等为伪终端(Pseudo-Terminal Slave),由 GUI 中打开的 Terminal 应用创建 - tty2 , tty3 为 Ctrl+Alt+F2/F3 切换的虚拟控制台 |
FROM | 用户来源地址。本地登录显示 :0 或空白;远程 SSH 显示客户端 IP |
LOGIN@ | 用户登录系统的时间戳 |
IDLE | 当前端口最后一次交互距今时间(如 3s , 2:59 ) |
JCPU | 与该终端关联的所有进程累计使用的 CPU 时间 |
PCPU | 当前正在运行的进程所占用的 CPU 时间 |
WHAT | 当前运行的命令(进程名),如 w , bash , /usr/lib/gnome-session-binary |
技术要点:
- 同一用户可在多个终端登录,形成多个 TTY/PTS 会话
idle
列可用于判断用户是否离席,辅助安全审计JCPU
和PCPU
可协助识别资源密集型会话
关键理解:
- 负载值反映的是 正在使用或等待 CPU 的进程数量。若系统为单核 CPU,负载持续 >1 即表示过载
双核则阈值为 2,依此类推 - 高负载长时间存在往往预示性能瓶颈或异常进程
可通过如下 Shell 脚本结合 NestJS 定时任务监控负载趋势:
ts
// src/monitor/system-monitor.service.ts
import { Injectable, Logger } from '@nestjs/common';
import { Cron } from '@nestjs/schedule';
import { exec } from 'child_process';
@Injectable()
export class SystemMonitorService {
private readonly logger = new Logger(SystemMonitorService.name);
@Cron('*/30 * * * *') // 每30秒执行一次
async checkSystemLoad() {
exec('cat /proc/loadavg', (error, stdout) => {
if (error) {
this.logger.error(`Load check failed: ${error.message}`);
return;
}
const [oneMin, fiveMin, fifteenMin] = stdout.trim().split(/\s+/).map(v => parseFloat(v));
this.logger.log(`Load Avg: ${oneMin} (1m), ${fiveMin} (5m), ${fifteenMin} (15m)`);
if (oneMin > 2) {
this.logger.warn('⚠️ High system load detected!');
}
});
}
}
3 ) TTY 与 PTS:理解终端类型
:0
:图形界面终端(X Server 主终端),代表本地 GUI 会话tty1
,tty2
...:虚拟控制台终端(Ctrl+Alt+F2~F6 切换)pts/0
,pts/1
...:伪终端(Pseudo Terminal Slave),由 SSH 或图形终端模拟器创建
例如启动多个 GNOME Terminal 窗口,每个都会分配一个 pts/N
编号
可补充以下代码实现 TTY 活动分析:
ts
// src/monitor/tty-analyzer.service.ts
import { Injectable } from '@nestjs/common';
import { execSync } from 'child_process';
@Injectable()
export class TtyAnalyzerService {
getActiveSessions(): Array<{
user: string;
tty: string;
from: string;
loginAt: string;
idle: string;
command: string;
}> {
try {
const output = execSync('w -h', { encoding: 'utf-8' });
return output
.trim()
.split('\n')
.map(line => {
const parts = line.trim().split(/\s+/);
return {
user: parts[0],
tty: parts[1],
from: parts[2],
loginAt: parts[3],
idle: parts[4],
command: parts.slice(8).join(' '), // 命令可能含空格
};
});
} catch (err) {
console.error('Failed to fetch w output:', err);
return [];
}
}
}
每个用户可通过多个 TTY 同时登录,且同一账户的不同终端将独立出现在 w
输出中
此外,who
命令可用于简化查询当前登录用户:
bash
$ who
oscar tty1 2025-04-05 07:02 (:0)
oscar pts/0 2025-04-05 07:17 (:0)
其输出等价于 w
命令中除进程信息外的部分,适用于脚本化检测用户在线状态。
4 ) 实际应用场景
当你发现服务器响应缓慢时,可立即执行:
bash
$ w
若看到某用户长时间运行高耗能脚本(如 find / -name "*.log"
),即可联系其终止操作或限制资源
ps
命令:静态进程快照分析
1 ) 概念定义
ps
(Process Status)命令提供某一时刻系统中所有进程的状态快照(snapshot)。它不会动态更新,适合配合管道进行筛选与排序
进程(Process)是已加载至内存并正在运行的程序实例。典型特征包括:
- 每个进程拥有唯一的 PID(Process ID)
- 可能衍生出多个子进程(如 Chrome 每标签页独立进程)
- Web 服务(Apache、Nginx)、数据库(MySQL、PostgreSQL)常以多进程模式运行
基本语法格式如下:
bash
ps [options]
常用选项组合包括:
ps aux
ps -ef
ps -u <username>
ps axjf
2 ) 常见用法及输出解析
2.1 ps
(无参数)------仅限当前终端进程
bash
$ ps
PID TTY TIME CMD
14806 pts/0 00:00:00 bash
16939 pts/0 00:00:00 ps
- PID:进程标识符
- TTY:所属终端
- TIME:累计 CPU 使用时间
- CMD:启动命令名称
注意:此模式下无法查看系统级或其他会话中的进程
仅显示当前 shell 及子进程,无法查看其他终端或系统级进程
2.2 ps -ef
------ 全系统进程列表(传统 Unix 风格)
bash
$ ps -ef
UID PID PPID C STIME TTY TIME CMD
root 1 0 0 07:02 ? 00:00:01 /sbin/init
root 2 0 0 07:02 ? 00:00:00 [kthreadd]
root 3 2 0 07:02 ? 00:00:00 [ksoftirqd/0]
wang 14806 1 0 07:17 pts/0 00:00:00 /bin/bash
wang 16939 14806 0 07:26 pts/0 00:00:00 ps -ef
关键列说明:
输出包含以下字段:
字段 | 含义 |
---|---|
UID | 运行该进程的用户 |
PID | 进程 ID |
PPID | 父进程 ID(Parent Process ID) |
C | CPU 使用占比(旧版) |
STIME | 启动时间 |
TTY | 控制终端 |
TIME | CPU 时间 |
CMD | 完整命令行 |
父子进程关系示例:
- 如
bash
(PID=14806) 是由init
(PID=1) 启动的 - 而
ps
命令是由bash
创建的子进程(PPID=14806)。
建议使用分页查看:
bash
$ ps -ef | less
示例代码解析进程树结构:
ts
// src/process/process-parser.service.ts
import { Injectable } from '@nestjs/common';
import { execSync } from 'child_process';
interface ProcessInfo {
uid: string;
pid: number;
ppid: number;
tty: string;
cmd: string;
}
@Injectable()
export class ProcessParserService {
getAllProcesses(): ProcessInfo[] {
const output = execSync('ps -eo uid,pid,ppid,tty,cmd --no-headers', {
encoding: 'utf-8',
});
return output.trim().split('\n').map(line => {
const match = line.match(/^\s*(\S+)\s+(\d+)\s+(\d+)\s+(\S+)\s+(.*)$/);
if (!match) return null;
return {
uid: match[1],
pid: parseInt(match[2], 10),
ppid: parseInt(match[3], 10),
tty: match[4],
cmd: match[5].trim(),
};
}).filter(Boolean) as ProcessInfo[];
}
getProcessTree(): Record<number, ProcessInfo[]> {
const processes = this.getAllProcesses();
const tree: Record<number, ProcessInfo[]> = {};
processes.forEach(proc => {
const parentPid = proc.ppid;
if (!tree[parentPid]) tree[parentPid] = [];
tree[parentPid].push(proc);
});
return tree;
}
}
2.3 ps aux
------ BSD 风格,含资源使用率
bash
$ ps aux
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
root 1 0.0 0.1 123456 7890 ? Ss 07:02 0:01 /sbin/init
oscarl 14806 0.0 0.2 234567 12345 pts/0 Ss 07:17 0:00 /bin/bash
...
新增重要字段:
字段 | 含义 |
---|---|
%CPU |
CPU 占用百分比 |
%MEM |
内存占用百分比 |
VSZ |
虚拟内存大小(KB) |
RSS |
物理内存驻留集大小(KB) |
STAT |
进程状态码(S=睡眠,R=运行,Z=僵尸等) |
2.4 按用户过滤:ps -u username
bash
$ ps -u oscarl
列出指定用户启动的所有进程。
2.5 树形结构显示:ps -efH
或 ps axjf
与 pstree
-H
参数使输出以缩进形式体现父子关系
更直观的方式是使用 pstree
命令,可视化整个进程层级
bash
$ ps axjf
PPID PID PGID SID TTY TPGID STAT UID TIME COMMAND
0 2 0 0 ? -1 S 0 0:00 [kthreadd]
2 3 0 0 ? -1 I< 0 0:00 \_ [rcu_gp]
2 4 0 0 ? -1 I< 0 0:00 \_ [rcu_par_gp]
...
缩进表示父子关系。更清晰的方式是使用 pstree
:
bash
$ pstree -p
systemd(1)
├─ModemManager(1234)
│ └─{ModemManager}(1235)
├─NetworkManager(1236)
│ ├─dhclient(1237)
│ └─{NetworkManager}(1238)
└─gnome-session(14806)
└─bash(14807)
└─pstree(16940)
这有助于识别服务依赖链及异常进程嵌套
3 ) 结合管道实现高级查询
按 CPU 使用率排序:
bash
$ ps aux --sort=-%cpu | head -10
--sort=-%cpu
表示按 CPU 使用率降序排列,head -10
显示前 10 条。
按内存使用排序:
bash
$ ps aux --sort=-%mem | head -10
综合排序(CPU + 内存)并取前十:
bash
$ ps aux --sort=-%cpu,-%mem | head -10
ps aux
提供更丰富的资源指标列:
bash
$ ps aux
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
root 1 0.0 0.3 169424 14840 ? Ss 07:02 0:01 /sbin/init
oscar 14806 0.0 0.2 11308 5124 pts/0 Ss 07:17 0:00 /bin/bash
firefox 15001 4.2 17.6 2100MB 140MB pts/0 Sl 07:20 2:15 /usr/lib/firefox/firefox
关键列包括:
- %CPU:CPU 占用率
- %MEM:内存占用率
- VSZ:虚拟内存大小(KB)
- RSS:物理内存驻留集大小(KB)
- STAT:进程状态码(S=睡眠,R=运行,Z=僵尸等)
按资源使用排序:ps aux --sort=-%cpu
与 --sort=-%mem
常用组合命令:
bash
按 CPU 使用率降序
ps aux --sort=-%cpu | head -10
按内存使用率降序
ps aux --sort=-%mem | head -10
综合排序:先按 CPU 再按内存
ps aux --sort=-%cpu,-%mem | head -10
此组合策略能快速锁定资源消耗大户,便于进一步排查或终止
4 ) 按用户过滤:ps -u [username]
仅查看特定用户的进程:
bash
$ ps -u oscar
PID TTY TIME CMD
14806 pts/0 00:00:00 bash
17012 pts/0 00:00:00 ps
同理,ps -u root
可聚焦系统守护进程
实战代码演示:基于 NestJS + TypeScript 的进程监控服务
1 ) 方案1
以下是一个完整的 NestJS 微服务模块,用于定期采集系统进程数据、计算负载趋势
并对外暴露 REST API 接口
项目结构概览
tree
/src
/system-monitor
system-monitor.controller.ts
system-monitor.service.ts
system-monitor.module.ts
main.ts
安装依赖
bash
npm install @nestjs/common @nestjs/core @nestjs/platform-express rxjs child_process
服务 system-monitor.service.ts
ts
// src/system-monitor/system-monitor.service.ts
import { Injectable } from '@nestjs/common';
import * as cp from 'child_process';
@Injectable()
export class SystemMonitorService {
/
* 执行 shell 命令并返回 Promise<string>
*/
private execCommand(command: string): Promise<string> {
return new Promise((resolve, reject) => {
cp.exec(command, (error, stdout, stderr) => {
if (error) return reject(error);
if (stderr) console.warn('STDERR:', stderr);
resolve(stdout.trim());
});
});
}
/
* 获取系统基本信息(时间、运行时长、负载、登录用户)
*/
async getSystemStatus() {
const uptimeRaw = await this.execCommand('uptime');
const wRaw = await this.execCommand('w');
// 解析 uptime 输出
const uptimeMatch = uptimeRaw.match(/up\s+(.+?),\s+(\d+)\s+user(s)?,\s+load average:\s+([\d.]+),\s+([\d.]+),\s+([\d.]+)/);
if (!uptimeMatch) throw new Error('Unable to parse uptime output');
const [, uptime, users, , load1, load5, load15] = uptimeMatch;
return {
current_time: new Date().toISOString(),
uptime,
users_logged_in: parseInt(users, 10),
load_average: {
'1m': parseFloat(load1),
'5m': parseFloat(load5),
'15m': parseFloat(load15),
},
raw_w_output: wRaw.split('\n'),
};
}
/
* 获取高资源占用进程(Top 10 by CPU & Memory)
*/
async getTopProcesses(limit = 10) {
const header = await this.execCommand(
"ps aux --no-header -o user,pid,%cpu,%mem,vsz,rss,tty,stat,start,time,comm | head -1"
);
const processesRaw = await this.execCommand(
`ps aux --no-header -o user,pid,%cpu,%mem,vsz,rss,tty,stat,start,time,comm | sort -k3nr -k4nr | head -${limit}`
);
const lines = processesRaw.trim().split('\n').filter(Boolean);
const parsed = lines.map(line => {
const parts = line.trim().split(/\s+/);
return {
user: parts[0],
pid: parseInt(parts[1], 10),
cpu_percent: parseFloat(parts[2]),
mem_percent: parseFloat(parts[3]),
vsz_kb: parseInt(parts[4], 10),
rss_kb: parseInt(parts[5], 10),
tty: parts[6],
stat: parts[7],
start: parts[8],
time: parts[9],
command: parts.slice(10).join(' '), // 处理命令含空格的情况
};
});
return {
total: parsed.length,
processes: parsed,
headers: [
'USER', 'PID', '%CPU', '%MEM', 'VSZ', 'RSS',
'TTY', 'STAT', 'START', 'TIME', 'COMMAND'
]
};
}
/
* 获取树形进程结构(简化版)
*/
async getProcessTree() {
const tree = await this.execCommand('pstree -p');
return { process_tree: tree };
}
}
控制器 system-monitor.controller.ts
ts
// src/system-monitor/system-monitor.controller.ts
import { Controller, Get } from '@nestjs/common';
import { SystemMonitorService } from './system-monitor.service';
@Controller('monitor')
export class SystemMonitorController {
constructor(private readonly monitorService: SystemMonitorService) {}
@Get('status')
async getStatus() {
return await this.monitorService.getSystemStatus();
}
@Get('processes/top')
async getTopProcesses() {
return await this.monitorService.getTopProcesses(10);
}
@Get('processes/tree')
async getProcessTree() {
return await this.monitorService.getProcessTree();
}
}
模块system-monitor.module.ts
ts
// src/system-monitor/system-monitor.module.ts
import { Module } from '@nestjs/common';
import { SystemMonitorController } from './system-monitor.controller';
import { SystemMonitorService } from './system-monitor.service';
@Module({
controllers: [SystemMonitorController],
providers: [SystemMonitorService],
})
export class SystemMonitorModule {}
主入口 main.ts
ts
// src/main.ts
import { NestFactory } from '@nestjs/core';
import { SystemMonitorModule } from './system-monitor/system-monitor.module';
async function bootstrap() {
const app = await NestFactory.create(SystemMonitorModule);
await app.listen(3000);
console.log('System Monitor API running on http://localhost:3000');
}
bootstrap();
启动与测试
bash
npx nest start
访问接口:
GET http://localhost:3000/monitor/status
GET http://localhost:3000/monitor/processes/top
GET http://localhost:3000/monitor/processes/tree
返回示例(节选):
json
{
"current_time": "2025-04-05T07:30:00.000Z",
"uptime": "28 min",
"users_logged_in": 2,
"load_average": { "1m": 0.77, "5m": 0.26, "15m": 0.12 },
"processes": [
{
"user": "oscarl",
"pid": 14806,
"cpu_percent": 2.4,
"mem_percent": 17.6,
"command": "firefox"
}
]
}
2 )方案2
实现一个简易的系统监控模块,用于采集并暴露关键指标
功能目标:
- 获取系统负载(
loadavg
) - 列出高 CPU/MEM 占用进程(模拟
ps aux --sort
) - 支持 HTTP 接口查询
安装依赖
bash
npm install child_process
若需定时任务:
npm install @nestjs/schedule
npm install rxjs
创建系统服务 (system.service.ts
)
ts
// src/system/system.service.ts
import { Injectable } from '@nestjs/common';
import * as childProcess from 'child_process';
@Injectable()
export class SystemService {
/
* 执行 shell 命令并返回 Promise 结果
*/
private execCommand(command: string): Promise<string> {
return new Promise((resolve, reject) => {
childProcess.exec(command, (error, stdout, stderr) => {
if (error) return reject(error);
if (stderr) return reject(new Error(stderr));
resolve(stdout.trim());
});
});
}
/
* 获取系统负载(1/5/15 分钟)
*/
async getLoadAverage(): Promise<number[]> {
const result = await this.execCommand('cat /proc/loadavg');
return result.split(' ').slice(0, 3).map(v => parseFloat(v));
}
/
* 获取系统运行时间(秒)
*/
async getUptime(): Promise<number> {
const result = await this.execCommand('cat /proc/uptime');
return parseInt(result.split(' ')[0], 10);
}
/
* 获取 top N 个高 CPU 使用率进程
*/
async getTopCPUProcesses(limit = 10): Promise<any[]> {
const cmd = `ps aux --sort=-%cpu | head -${limit + 1} | tail -n ${limit}`;
const output = await this.execCommand(cmd);
return this.parsePsOutput(output);
}
/
* 获取 top N 个高内存使用率进程
*/
async getTopMemoryProcesses(limit = 10): Promise<any[]> {
const cmd = `ps aux --sort=-%mem | head -${limit + 1} | tail -n ${limit}`;
const output = await this.execCommand(cmd);
return this.parsePsOutput(output);
}
/
* 解析 ps 输出为结构化对象数组
*/
private parsePsOutput(output: string): any[] {
const lines = output.trim().split('\n');
const headers = lines[0].split(/\s+/);
return lines.slice(1).map(line => {
const values = line.split(/\s+/);
const entry = {};
headers.forEach((header, index) => {
entry[header.toLowerCase()] = values[index];
});
return entry;
});
}
}
控制器接口 (system.controller.ts
)
ts
// src/system/system.controller.ts
import { Controller, Get } from '@nestjs/common';
import { SystemService } from './system.service';
@Controller('system')
export class SystemController {
constructor(private readonly systemService: SystemService) {}
@Get('loadavg')
async getLoadAvg() {
const loadavg = await this.systemService.getLoadAverage();
return { loadavg, unit: '1/5/15min' };
}
@Get('uptime')
async getUpTime() {
const seconds = await this.systemService.getUptime();
const days = Math.floor(seconds / 86400);
const hours = Math.floor((seconds % 86400) / 3600);
return { uptime_seconds: seconds, formatted: `${days}d ${hours}h` };
}
@Get('top-cpu')
async getTopCPU() {
const processes = await this.systemService.getTopCPUProcesses(10);
return { total: processes.length, processes };
}
@Get('top-mem')
async getTopMEM() {
const processes = await this.systemService.getTopMemoryProcesses(10);
return { total: processes.length, processes };
}
}
模块注册 (system.module.ts
)
ts
// src/system/system.module.ts
import { Module } from '@nestjs/common';
import { SystemController } from './system.controller';
import { SystemService } from './system.service';
@Module({
controllers: [SystemController],
providers: [SystemService],
})
export class SystemModule {}
启动并测试
访问接口示例:
GET /system/loadavg
→ 返回[0.77, 0.26, 0.12]
GET /system/top-cpu
→ 返回前 10 个高 CPU 进程GET /system/top-mem
→ 返回前 10 个高内存进程
3 ) 方案3
集成至 NestJS 服务中进行资源告警 核心代码:
ts
// src/alert/resource-alert.service.ts
import { Injectable, OnModuleInit } from '@nestjs/common';
import { execSync } from 'child_process';
@Injectable()
export class ResourceAlertService implements OnModuleInit {
private readonly cpuThreshold = 80; // 百分比
private readonly memThreshold = 70;
async onModuleInit() {
setInterval(() => this.checkResourceUsage(), 60000); // 每分钟检查
}
private checkResourceUsage() {
try {
const topCpuProc = execSync(
"ps aux --sort=-%cpu | awk 'NR==2{print $11, $3, $4}'",
{ timeout: 5000, encoding: 'utf-8' }
).trim().split(' ');
const [cmd, cpu, mem] = topCpuProc;
const cpuVal = parseFloat(cpu);
const memVal = parseFloat(mem);
if (cpuVal > this.cpuThreshold) {
console.warn(`🚨 High CPU: ${cmd} using ${cpuVal}%`);
}
if (memVal > this.memThreshold) {
console.warn(`🚨 High Memory: ${cmd} using ${memVal}%`);
}
} catch (err) {
console.error('Resource check error:', err.message);
}
}
}
动态进程监控:top
命令概述
尽管本文未展开 top
命令细节,但需强调其核心价值:提供实时刷新的动态进程视图,支持交互式操作(如按 P
排序 CPU、M
排序内存、k
终止进程)。
对比总结:
特性 | ps |
top |
---|---|---|
数据性质 | 静态快照(Snapshot) | 动态更新 |
刷新机制 | 手动执行 | 自动刷新(默认 3 秒) |
交互能力 | 无 | 支持按键操作 |
资源开销 | 极低 | 较高 |
适用场景 | 脚本化、日志记录 | 实时排查、人工干预 |
说明与最佳实践
1 ) 负载过高时的应对策略
- 使用
top
实时观察(见下文) - 查找异常进程:
ps aux --sort=-%cpu | head -5
- 终止进程:
kill -9 <PID>
或pkill firefox
- 设置资源限制:
ulimit -v 1000000
(限制虚拟内存)
2 ) 为什么 Linux 不需要频繁重启?
- 内核热补丁支持(Live Patching)
- 动态加载模块(Loadable Kernel Modules,LKM)
总结与核心要点提炼
本文系统梳理了 Linux 下三大核心监控命令的技术细节与应用场景:
工具 | 类型 | 核心用途 |
---|---|---|
w |
静态快照 | 查看登录用户、终端行为、系统负载 |
ps |
静态快照 | 获取进程列表、父子关系、资源占用 |
top |
动态监控 | 实时追踪 CPU/MEM 消耗最高的进程 |
在此基础上,通过 NestJS 后端服务封装,实现了将传统 Shell 能力转化为 RESTful API 的工程实践路径,为后续构建可视化监控平台(如 Grafana + Prometheus)打下坚实基础。
最终建议:
- 在生产环境中应结合日志审计(
auditd
)、容器监控(cgroups)、系统调用跟踪(strace
)等手段,形成多层次、立体化的系统可观测性架构
w
命令是系统健康的第一道防线:快速掌握谁在登录、系统负载如何、是否存在异常空闲或活跃会话- 负载平均值需结合 CPU 核心数解读:单核负载 >1 即过载,多核线性扩展判断标准
ps
提供不可替代的静态进程视图:尤其适合脚本采集、自动化分析- 合理利用
ps aux --sort
实现资源热点定位:精准识别占用 CPU 或内存最高的进程 - 父子进程关系决定系统稳定性:误杀父进程可能导致连锁崩溃,应优先终止叶子节点
所有命令均基于 POSIX 标准设计,适用于主流 Linux 发行版(Ubuntu、CentOS、Debian 等)。生产环境建议结合 htop
、glances
等增强工具提升可观测性