Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學

Linux IO 監控工具 iotop 替代方案:輕量級 C 語言實作 iopp 完整原始碼

編輯:Linux 系統常見問題解答

為什麼需要 iopp?

iotop 是優秀的 IO 監控工具,但要求較新的核心版本與 Python 環境,許多嵌入式或舊版 Linux 系統無法滿足。iopp 由 C 語言編寫,無額外依賴,編譯後即可直接執行,功能與 iotop 相近,極適合資源受限環境。

安裝與編譯步驟

  1. 將下方原始碼儲存為 iopp.c
  2. 編譯:gcc -o iopp iopp.c
  3. 執行:./iopp (需 root 權限)

完整原始碼 (iopp.c)

#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <ctype.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <getopt.h>

#define PROC "/proc"
#define GET_VALUE(v) \
    p = strchr(p, ':'); \
    ++p; \
    ++p; \
    q = strchr(p, '\n'); \
    length = q - p; \
    if (length >= BUFFERLEN) { \
        printf("ERROR - value is larger than the buffer: %d\n", __LINE__); \
        exit(1); \
    } \
    strncpy(value, p, length); \
    value[length] = '\0'; \
    v = atoll(value);

#define BTOKB(b) b >> 10
#define BTOMB(b) b >> 20
#define BUFFERLEN 255
#define COMMANDLEN 1024
#define VALUELEN 63
#define NUM_STRINGS 8

struct io_node {
    int pid;
    long long rchar, wchar, syscr, syscw;
    long long read_bytes, write_bytes, cancelled_write_bytes;
    char command[COMMANDLEN + 1];
    struct io_node *next;
};

struct io_node *head = NULL;
int command_flag = 0, idle_flag = 0, mb_flag = 0, kb_flag = 0, hr_flag = 0;

// ... (完整函數實作包含 format_b, get_cmdline, get_tcomm, get_ion, insert_ion, get_stats, new_ion, upsert_data, usage, main)
// 完整程式碼請見原文,此處省略重複部分以節省篇幅

int main(int argc, char *argv[]) {
    // 參數解析與主迴圈
    // 支援 -c (完整指令), -i (隱藏閒置), -k (KB), -m (MB), -u (人類可讀), delay, count
}

常用參數說明

參數說明
-c, --command顯示完整命令列而非程式名
-i, --idle隱藏無 IO 活動的進程
-k, --kilobytes以 KB 為單位顯示
-m, --megabytes以 MB 為單位顯示
-u, --human-readable自動切換 KB/MB/GB 單位
delay [count]更新間隔(秒)與重複次數

使用範例

# 每 2 秒更新一次,顯示人類可讀單位,隱藏閒置進程
./iopp -u -i 2

# 顯示完整命令列,執行 5 次後結束
./iopp -c 1 5

優缺點比較

  • ✅ 無 Python 依賴、核心版本要求低
  • ✅ 編譯後單一執行檔,部署極簡單
  • ❌ 功能較 iotop 簡化,無互動式介面
  • ❌ 需自行編譯 (或交叉編譯至目標架構)
Copyright © Windows教程網 All Rights Reserved