源碼分析共享地址:https://github.com/fivezh/WebBench
下載源碼后編譯源程序后即可執行:
sudo make clean
sudo make & make install
1. 使用方法
five@master:~/github/OpenCCode/WebBench$ ./webbench webbench [option]... URL -f|--force Don't wait for reply from server. -r|--reload Send reload request - Pragma: no-cache. -t|--time <sec> Run benchmark for <sec> seconds. Default 30. -p|--proxy <server:port> Use proxy server for request. -c|--clients <n> Run <n> HTTP clients at once. Default one. -9|--http09 Use HTTP/0.9 style requests. -1|--http10 Use HTTP/1.0 protocol. -2|--http11 Use HTTP/1.1 protocol. --get Use GET request method. --head Use HEAD request method. --options Use OPTIONS request method. --trace Use TRACE request method. -?|-h|--help This information. -V|--version Display program version.
實例:./webbench -t 10 -c 50 http://www.baidu.com/
five@master:~/github/OpenCCode/WebBench$ ./webbench -t 10 -c 50 http://www.baidu.com/ Webbench - Simple Web Benchmark 1.5 Copyright (c) Radim Kolar 1997-2004, GPL Open Source Software. Benchmarking: GET http://www.baidu.com/ 50 clients, running 10 sec. Speed=492 pages/min, 918494 bytes/sec. Requests: 82 susceed, 0 failed.
2. 源碼分析
2.1 volatile關鍵詞
volatile用法總結:(不希望編譯器優化、多任務程序可能隨時更改、設計硬件寄存器時)
volatile的使用的場合大致有以下幾點:
1、中斷服務程序中修改的供其它程序檢測的變量需要加volatile;
2、多任務環境下各任務間共享的標志應該加volatile;
3、存儲器映射的硬件寄存器通常也要加volatile說明,因為每次對它的讀寫都可能有不同意義。
參考:[1] C語言的那些小秘密之volatile [2] C中的volatile用法
2.2 #ifndef 和#if !defined的區別
二者均可用於判斷是否已進行宏定義,區別之處在於后者更適用於多重判別條件的情形。
如: #if defined(UNIX) && !defined(AIX)
參考:[3] stackoverflow:difference-between-ifndef-and-if-defined-in-c
2.3 getopt_long函數
除getopt()提供的短選項(short options, 比如-s)解析外,還提供長選項(long options,比如--name)解析,參數原型為:
#include <unistd.h>
int getopt(int argc, char * const argv[],
const char *optstring);
extern char *optarg;
#include <getopt.h> int getopt_long(int argc, char * const argv[], const char *optstring, const struct option *longopts, int *longindex);
getopt_long() and getopt_long_only()
The getopt_long() function works like getopt() except that it also
accepts long options, started with two dashes. (If the program accepts
only long options, then optstring should be specified as an empty
string (""), not NULL.) Long option names may be abbreviated if the
abbreviation is unique or is an exact match for some defined option. A
long option may take a parameter, of the form --arg=param or --arg
param.
參考:[4] linux 中解析命令行參數 (getopt_long用法) [5]Wikipedia getopt() [6] IBM 使用 getopt() 進行命令行處理【推薦閱讀】
注意:注意的是默認情況下getopt會重新排列命令行參數的順序,所以到最后所有不包含選項的命令行參數都排到最后(參考)。
幾個重要全局變量:
optarg:處理帶輸入參數的選項時,選項參數保存至char *optarg中。
optind:下一個處理的選項在argv中的地址,所有選項處理完后,optind指向未識別的項。
optopt:最后一個已知項。
問題1:該函數的實現是如何做的?
答:getopt()的GNU實現,getopt_long()的NetBSD實現 ,一種getopt_long()的簡單實現。
問題2:當短參數作為輸入時,該函數如何返回?
答:getopt_long()是同時支持長選項和短選項的getopt()實現。
2.4