我想分析 Linux C 運行庫各頭檔的使用頻率,藉此大致判斷哪些 C 庫頭檔是常用、基礎或重要的,為 Linux 系統編程學習者提供一個方向。最精細的統計其實應針對系統呼叫與 C 標準庫函式,對初學者更有指导意义,但目前還不知如何實現,於是選擇以 BusyBox 為研究對象——它主要依賴 Linux C 運行庫來實作各種命令與工具。
BusyBox 整合了一百多個最常用的 Linux 命令與工具,從 ls、cat、echo 到 grep、find、mount、telnet,被稱為「Linux 工具裡的瑞士軍刀」,也內含 Android 自帶的 shell。
先搜尋 BusyBox 源碼,取出所有含 include 的程式碼行:
find -name '*.c' -o -name '*.h' | xargs grep include > busybox-stats.txt
輸出範例:
./console-tools/openvt.c:#include<linux/vt.h>
./console-tools/showkey.c:#include<linux/kd.h>
./console-tools/loadfont.c:#include<sys/kd.h>
接著在 NotePad++ 中過濾、排序,得到形如 arpa/inet.h(出現 7 次)、asm/types.h 等的清單,這些正是 Linux C 運行庫的頭檔。
接下來寫一個 Java 程式,統計每個頭檔在文字檔中出現的次數並排序。工程目錄結構為 E:\workspace\JavaApp\WordStats,內含 busybox-stats.txt 與 WordStats.java。
WordStats.java:
import java.io.*;
import java.util.*;
import java.util.Map.Entry;
import java.text.DecimalFormat;
public class WordStats {
public static void main(String[] args) throws IOException {
int argc = args.length;
String inputFilename, outputFilename;
if (argc == 2) {
inputFilename = args[0];
outputFilename = args[1];
} else {
System.out.println("usage: java WordStats <inputfile> <outputfile>");
return;
}
BufferedReader in = new BufferedReader(new FileReader(inputFilename));
PrintWriter out = new PrintWriter(new FileWriter(outputFilename));
Map<String, Integer> stats = new HashMap<String, Integer>();
String str;
while ((str = in.readLine()) != null) {
if (stats.containsKey(str)) {
Integer count = stats.get(str);
stats.put(str, ++count);
} else {
stats.put(str, 1);
}
}
ArrayList<Entry<String,Integer>> l = new ArrayList<Entry<String,Integer>>(stats.entrySet());
Collections.sort(l, new Comparator<Map.Entry<String, Integer>>() {
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
return (o2.getValue() - o1.getValue());
}
});
for (Entry<String, Integer> e : l) {
out.println(new DecimalFormat("000").format(e.getValue()) + " " + e.getKey());
}
in.close();
out.close();
}
}
程式以 HashMap 累加各頭檔出現次數,再用 ArrayList 搭配 Comparator 依值遞減排序,最後以 DecimalFormat 補零格式化輸出。
更多詳情見請繼續閱讀下一頁的精彩內容: https://www.linuxidc.com/Linux/2014-04/100688p2.htm