問題描述:
今天想做一個(gè)簡(jiǎn)單的HTTP服務(wù)器,發(fā)現(xiàn)libevent使用很方便,就用他的example里的httpserver代碼試了下,發(fā)現(xiàn)一個(gè)問題,就是在打開部分文件時(shí)候,服務(wù)器會(huì)卡住。沒有任何返回,瀏覽器一直處于等待狀態(tài)。
后來調(diào)試后發(fā)現(xiàn),卡死在evbuffer_add_file函數(shù)。
源代碼如下:
01 /* Otherwise it's a file; add it to the buffer to get
02 * sent via sendfile */
03 const char *type = guess_content_type(decoded_path);
04 if ((fd = open(whole_path, O_RDONLY)) < 0) {
05 perror("open");
06 goto err;
07 }
08 if (fstat(fd, &st)<0) {
09 /* Make sure the length still matches, now that we
10 * opened the file :/ */
11 perror("fstat");
12 goto err;
13 }
14 evhttp_add_header(evhttp_request_get_output_headers(req),
15 "Content-Type", type);
16 evbuffer_add_file(evb, fd, 0, st.st_size);
后經(jīng)過調(diào)試發(fā)現(xiàn),是由于代碼第四行中打開文件的方式有問題。缺少O_BINARY標(biāo)志,導(dǎo)致對(duì)于某些包含不可顯示或者中文的文件會(huì)卡死。
改成如下代碼即可:
1 /* Otherwise it's a file; add it to the buffer to get
2 * sent via sendfile */
3 const char *type = guess_content_type(decoded_path);
4 if ((fd = open(whole_path, O_RDONLY|O_BINARY)) < 0) {
5 perror("open");
6 goto err;
7 }