parsePs static method

List<ProcessInfo> parsePs(
  1. String content, {
  2. int limit = 20,
})

Parses POSIX ps output with columns pid %cpu rss comm (rss in kB). The header line is skipped. Results are sorted by CPU descending and truncated to limit.

Implementation

static List<ProcessInfo> parsePs(String content, {int limit = 20}) {
  final lines = content.trim().split('\n');
  final out = <ProcessInfo>[];
  for (final line in lines.skip(1)) {
    final cols = line.trim().split(RegExp(r'\s+'));
    if (cols.length < 4) continue;
    final pid = int.tryParse(cols[0]) ?? 0;
    final cpu = double.tryParse(cols[1]) ?? 0;
    final rss = (int.tryParse(cols[2]) ?? 0) * 1024;
    final name = cols.sublist(3).join(' ');
    if (pid == 0) continue;
    out.add(
      ProcessInfo(pid: pid, name: name, cpuPercent: cpu, memoryBytes: rss),
    );
  }
  out.sort((a, b) => b.cpuPercent.compareTo(a.cpuPercent));
  return out.take(limit).toList();
}