標籤:des style blog http io color os ar 使用
Webbench
Webbench是一個在linux下使用的非常簡單的網站壓測工具。它使用fork()類比多個用戶端同時訪問我們設定的URL,測試網站在壓力下工作的效能,最多可以類比3萬個並發串連去測試網站的負載能力。Webbench使用C語言編寫, 代碼實在太簡潔,源碼加起來不到600行。
webbench壓測的命令:
webbench -c 300 -t 10 url
其中:-c 300 表示並發數(可以了理解成用戶端),
-t 10表示時間(秒)
url 想要壓測的url
下載連結:http://home.tiscali.cz/~cz210552/webbench.html
整個代碼的流程圖如下:
一、首先我們從主函數入手,前面幾個都是初始設定變數,沒什麼好說的,出現了一個getopt_long函數,應該有些人沒有用過這個函數,我先來分析下這個函數吧~
int getopt_long(int argc, char * const argv[],const char *optstring,const struct option *longopts, int *longindex);
1、前兩個參數,就是main函數的argc和argv,這兩者直接傳入即可,
2、optstring的格式舉例說明比較方便,例如:char *optstring = "abcd:";
上面這個optstring在傳入之後,getopt函數將依次檢查命令列是否指定了 -a, -b, -c及 -d,(這需要多次調用getopt函數,直到其返回-1),當檢查到上面某一個參數被指定時,函數會返回被指定的參數名稱(即該字母),最後一個參數d後面帶有冒號,: 表示參數d是可以指定值的,如 -d 100 或 -d user。
3、longopts指向的是一個由option結構體組成的數組,那個數組的每個元素,指明了一個“長參數”(即形如--name的參數)名稱和性質:
struct option {
const char *name;
int has_arg;
int *flag;
int val;
};
name 是參數的名稱
has_arg 指明是否帶參數值,其數值可選:
no_argument (即 0) 表明這個長參數不帶參數(即不帶數值,如:--name)
required_argument (即 1) 表明這個長參數必須帶參數(即必須帶數值,如:--name Bob)
optional_argument(即2)表明這個長參數後面帶的參數是可選的,(即--name和--name Bob均可)
flag 當這個指標為空白的時候,函數直接將val的數值從getopt_long的返回值返回出去,當它非空時,val的值會被賦到flag指向的整型數中,而函數返回值為0
val 用於指定函數找到該選項時的返回值,或者當flag非空時指定flag指向的資料的值。
static const struct option long_options[]={ {"force",no_argument,&force,1}, {"reload",no_argument,&force_reload,1}, {"time",required_argument,NULL,'t'}, //bench的測試時間 預設為30s {"help",no_argument,NULL,'?'}, {"http09",no_argument,NULL,'9'}, {"http10",no_argument,NULL,'1'}, {"http11",no_argument,NULL,'2'}, {"get",no_argument,&method,METHOD_GET}, {"head",no_argument,&method,METHOD_HEAD}, {"options",no_argument,&method,METHOD_OPTIONS}, {"trace",no_argument,&method,METHOD_TRACE}, {"version",no_argument,NULL,'V'}, {"proxy",required_argument,NULL,'p'}, {"clients",required_argument,NULL,'c'}, {NULL,0,NULL,0}};4、option_index指向的變數將記錄當前找到參數符合longopts裡的第幾個元素的描述,即是longopts的下標值。
例如對於
while ( (opt = getopt_long(argc, argv, optstring, long_options, &option_index)) != -1) { printf("opt = %c\n", opt); //被指定的參數名稱(即該字母) printf("optarg = %s\n", optarg); //optarg為參數的指定值 printf("optind = %d\n", optind); //下一個將被處理到的參數在argv中的下標值。 printf("argv[optind - 1] = %s\n", argv[optind - 1]); printf("option_index = %d\n", option_index); //它指向的變數將記錄當前找到參數符合longopts裡的第幾個元素的描述,即是longopts的下標值。 }
輸入命令列test_getopt_long -reqarg 100
輸出:
opt = reqarg
optarg = 100
optind = 3
argv[optind - 1] = 100
二、build_request函數
目的是對url進行處理,得到host,proxyport,request
其中request就是之後利用socket與host通訊所要發送的報文。
void build_request(const char *url){ char tmp[10]; int i; bzero(host,MAXHOSTNAMELEN); //置host字串前MAXHOSTNAMELEN個位元組為零且包括‘\0’。 bzero(request,REQUEST_SIZE); if(force_reload && proxyhost!=NULL && http10<1) http10=1; if(method==METHOD_HEAD && http10<1) http10=1; if(method==METHOD_OPTIONS && http10<2) http10=2; if(method==METHOD_TRACE && http10<2) http10=2; switch(method) { default: case METHOD_GET: strcpy(request,"GET");break; case METHOD_HEAD: strcpy(request,"HEAD");break; case METHOD_OPTIONS: strcpy(request,"OPTIONS");break; case METHOD_TRACE: strcpy(request,"TRACE");break; } strcat(request," "); if(NULL==strstr(url,"://")) { fprintf(stderr, "\n%s: is not a valid URL.\n",url); exit(2); } if(strlen(url)>1500) { fprintf(stderr,"URL is too long.\n"); exit(2); } if(proxyhost==NULL) if (0!=strncasecmp("http://",url,7)) { fprintf(stderr,"\nOnly HTTP protocol is directly supported, set --proxy for others.\n"); exit(2); } /* protocol/host delimiter */ i=strstr(url,"://")-url+3; //找到url中://的出現的位置 /* printf("%d\n",i); */ if(strchr(url+i,'/')==NULL) {//判斷url中除去http://後是否存在'/' fprintf(stderr,"\nInvalid URL syntax - hostname don't ends with '/'.\n"); exit(2); } if(proxyhost==NULL)//if裡面都是為了擷取連接埠號碼 主機名稱 和 request {//比如url="http://localhost:12345/test"; //if運行結束後 proxyport=12345,host=localhost /* get port from hostname */ if(index(url+i,':')!=NULL && index(url+i,':')<index(url+i,'/')) { strncpy(host,url+i,strchr(url+i,':')-url-i); //char *strncpy(char *destin, char *source, int //maxlen),把src所指由NULL結束的字串的前n個位元組複製到dest所指的數組中。 bzero(tmp,10); strncpy(tmp,index(url+i,':')+1,strchr(url+i,'/')-index(url+i,':')-1); /* printf("tmp=%s\n",tmp); */ proxyport=atoi(tmp); if(proxyport==0) proxyport=80; } else { strncpy(host,url+i,strcspn(url+i,"/")); } // printf("Host=%s\n",host); strcat(request+strlen(request),url+i+strcspn(url+i,"/")); } else { // printf("ProxyHost=%s\nProxyPort=%d\n",proxyhost,proxyport); strcat(request,url); } if(http10==1) strcat(request," HTTP/1.0"); else if (http10==2) strcat(request," HTTP/1.1"); strcat(request,"\r\n"); if(http10>0) strcat(request,"User-Agent: WebBench "PROGRAM_VERSION"\r\n"); if(proxyhost==NULL && http10>0) { strcat(request,"Host: "); strcat(request,host); strcat(request,"\r\n"); } if(force_reload && proxyhost!=NULL) { strcat(request,"Pragma: no-cache\r\n"); } if(http10>1) strcat(request,"Connection: close\r\n"); /* add empty line at end */ if(http10>0) strcat(request,"\r\n"); // printf("Req=%s\n",request);}
三、bench函數
該函數主要採用fork出子進程來測試網站,並且利用主進程來讀取所有子進程寫入的資料,每個子進程調用benchcore函數來測試存到全域變數speed faulted,
最後主進程匯總各個子線程的資料顯示出來~
/* vraci system rc error kod */static int bench(void){ int i,j,k; pid_t pid=0; FILE *f; /* check avaibility of target server */ i=Socket(proxyhost==NULL?host:proxyhost,proxyport); //測試網站是否能連 if(i<0) { fprintf(stderr,"\nConnect to server failed. Aborting benchmark.\n"); return 1; } close(i); /* create pipe */ if(pipe(mypipe)) { perror("pipe failed."); return 3; } /* not needed, since we have alarm() in childrens */ /* wait 4 next system clock tick */ /* cas=time(NULL); while(time(NULL)==cas) sched_yield(); */ /* fork childs */ for(i=0;i<clients;i++) { pid=fork(); // 1)在父進程中,fork返回新建立子進程的進程ID; //2)在子進程中,fork返回0; // 3)如果出現錯誤,fork返回一個負值; if(pid <= (pid_t) 0) { /* child process or error*/ sleep(1); /* make childs faster */ break; } } if( pid< (pid_t) 0) { fprintf(stderr,"problems forking worker no. %d\n",i); perror("fork failed."); return 3; } if(pid== (pid_t) 0) { /* I am a child */ if(proxyhost==NULL) benchcore(host,proxyport,request); //bench的核心代碼 子進程進入此函數測試網站,直到benchtime耗完為止 else benchcore(proxyhost,proxyport,request); /* write results to pipe */ f=fdopen(mypipe[1],"w"); if(f==NULL) { perror("open pipe for writing failed."); return 3; } /* fprintf(stderr,"Child - %d %d\n",speed,failed); */ fprintf(f,"%d %d %d\n",speed,failed,bytes);//各個子進程往pipe中寫入測試結果 fclose(f); return 0; } else { f=fdopen(mypipe[0],"r"); if(f==NULL) { perror("open pipe for reading failed."); return 3; } setvbuf(f,NULL,_IONBF,0); //setvbuf 就是設定檔案流的buffer配置,如setvbuf(input, bufr, _IOFBF, 512)是設定 input這個檔案流使用 bufr //所指的512個位元組作為 input檔案的buffer, 當你操作input檔案時,資料都會暫存在 bufr //裡面,每次讀input時,系統會一次性讀512位元組到bufr裡暫存。 speed=0; failed=0; bytes=0; while(1) { pid=fscanf(f,"%d %d %d",&i,&j,&k);//主進程從pipe中讀取每個子進程寫的資料分別讀取到i,j,k中,由於pipe在空時,會被阻塞 if(pid<2) { fprintf(stderr,"Some of our childrens died.\n"); break; } speed+=i; failed+=j; bytes+=k; /* fprintf(stderr,"*Knock* %d %d read=%d\n",speed,failed,pid); */ if(--clients==0) break; //當讀取完所有子進程寫入的結果後 主進程結束 } fclose(f); printf("\nSpeed=%d pages/min, %d bytes/sec.\nRequests: %d susceed, %d failed.\n", (int)((speed+failed)/(benchtime/60.0f)), (int)(bytes/(float)benchtime), speed, failed); //輸出所有子進程記錄資料之和的結果 } return i;}
四、benchcore函數
該函數主要採用socket串連、發送request、接收來測試網站,測試結果存在全域變數speed faulted,bytes
定時時間結束則退出函數~
其中關於sigaction函數的使用:
int sigaction(int signo,const struct sigaction *restrict act,struct sigaction *restrict oact);
其中signo的資訊可參考:http://blog.csdn.net/liucimin/article/details/40507443
其中結構sigaction定義如下:
struct sigaction{ void (*sa_handler)(int); sigset_t sa_mask; int sa_flag; void (*sa_sigaction)(int,siginfo_t *,void *);};
sa_handler欄位包含一個訊號捕捉函數的地址
sa_flag標誌。
void benchcore(const char *host,const int port,const char *req){ int rlen; char buf[1500]; int s,i; struct sigaction sa; /* setup alarm signal handler */ //設定定時器,該進程benchtime之後結束測試 sa.sa_handler=alarm_handler; sa.sa_flags=0; if(sigaction(SIGALRM,&sa,NULL)) //通過訊號設定時間結束後全域變數timerexpired的值 exit(3); alarm(benchtime);//alarm也稱為鬧鐘函數,它可以在進程中設定一個定時器,當定時器指定的時間到時//,它向進程發送SIGALRM訊號。如果忽略或者不捕獲此訊號//,則其預設動作是終止調用該alarm函數的進程。 rlen=strlen(req); nexttry:while(1) { if(timerexpired)//到點後結束函數 { if(failed>0) { /* fprintf(stderr,"Correcting failed by signal\n"); */ failed--; } return; } s=Socket(host,port); //Socket是標頭檔中自己寫的函數,返回socket串連後的結果 if(s<0) { failed++;continue;} if(rlen!=write(s,req,rlen)) {failed++;close(s);continue;} //往伺服器發request if(http10==0) if(shutdown(s,1)) { failed++;close(s);continue;} if(force==0) { /* read all available data from socket */ while(1) { if(timerexpired) break; i=read(s,buf,1500); //成功返回讀取的位元組數,出錯返回-1並設定errno,如果在調read之前已到達檔案末尾,則這次read返回0 /* fprintf(stderr,"%d\n",i); */ if(i<0) //讀取失敗 failed++,重新發送request讀資料 { failed++; close(s); goto nexttry; } else if(i==0) break; else bytes+=i; } } if(close(s)) {failed++;continue;} speed++; }}
最值得關注的10個C開源項目之Webbench源碼分析