getResourceUsage 获取进程资源使用情况
(pid int)
| 337 | |
| 338 | // getResourceUsage 获取进程资源使用情况 |
| 339 | func (t *BashOutputTool) getResourceUsage(pid int) *ResourceUsage { |
| 340 | if pid <= 0 { |
| 341 | return nil |
| 342 | } |
| 343 | |
| 344 | // 使用ps命令获取资源使用情况 |
| 345 | cmd := exec.Command("ps", "-p", strconv.Itoa(pid), "-o", "%cpu,rss,vsz", "--no-headers") |
| 346 | output, err := cmd.Output() |
| 347 | if err != nil { |
| 348 | return nil |
| 349 | } |
| 350 | |
| 351 | // 解析输出 |
| 352 | fields := strings.Fields(strings.TrimSpace(string(output))) |
| 353 | if len(fields) < 3 { |
| 354 | return nil |
| 355 | } |
| 356 | |
| 357 | var cpu float64 |
| 358 | var memory int64 |
| 359 | _, _ = fmt.Sscanf(fields[0], "%f", &cpu) |
| 360 | _, _ = fmt.Sscanf(fields[1], "%d", &memory) |
| 361 | memory *= 1024 // 转换为字节 |
| 362 | |
| 363 | return &ResourceUsage{ |
| 364 | CPU: cpu, |
| 365 | Memory: memory, |
| 366 | DiskIO: 0, // 简化实现,不获取磁盘IO |
| 367 | } |
| 368 | } |
| 369 | |
| 370 | func (t *BashOutputTool) Prompt() string { |
| 371 | return `获取后台运行shell的输出和状态信息。 |