2014-09-03 948 views
1

我用libevent2.1.1來編寫一個簡單的http服務器,我想我應該在http_server_callback中發佈evhttp_requestevhttp_request_free。但是當我運行它時,發生錯誤。請告訴我爲什麼,以及我該怎麼做。我應該叫evhttp_request_free釋放http服務器中的資源嗎?

enter image description here

void http_server_callback (struct evhttp_request *req, void *arg) 
{ 
    evhttp_send_reply (req, HTTP_OK, "OK", NULL); 

    evhttp_request_free(req); 
} 

int http_server_run (void) 
{ 
    struct event_base *base; 
    struct evhttp *http; 
    struct evhttp_bound_socket *handle; 

    base = event_base_new(); 
    if (! base) 
    { 
     fprintf (stderr, "Couldn't create an event_base: exiting\n"); 
     return 1; 
    } 

    http = evhttp_new (base); 
    if (! http) 
    { 
     fprintf (stderr, "couldn't create evhttp. Exiting.\n"); 
     return 1; 
    } 

    evhttp_set_gencb (http, http_server_callback, NULL); 

    handle = evhttp_bind_socket_with_handle (http, "127.0.0.1", 8888); 
    if (! handle) 
    { 
     fprintf (stderr, "couldn't bind to port 8888. Exiting.\n"); 
     return 1; 
    } 

    event_base_dispatch (base); 

    return 0; 
} 

int main (void) 
{ 
    WSADATA WSAData; 
    WSAStartup (0x101, &WSAData); 

    http_server_run(); 

    return 0; 
} 

在此先感謝

+0

顯示完整的碼,錯誤的細節。 – jfly 2014-09-03 04:37:39

+0

謝謝,jfly!我修改了這個問題,併發布完整的代碼和錯誤圖。 – 2014-09-03 07:14:20

回答

1

req將在回調函數evhttp_send_done當服務器寫完被釋放。所以它會導致雙倍免費。
中的libevent的源代碼:

static void 
evhttp_send_done(struct evhttp_connection *evcon, void *arg) 
{ 
    int need_close; 
    struct evhttp_request *req = TAILQ_FIRST(&evcon->requests); 
    TAILQ_REMOVE(&evcon->requests, req, next); 

    need_close = 
     (REQ_VERSION_BEFORE(req, 1, 1) && 
     !evhttp_is_connection_keepalive(req->input_headers))|| 
     evhttp_is_connection_close(req->flags, req->input_headers) || 
     evhttp_is_connection_close(req->flags, req->output_headers); 

    EVUTIL_ASSERT(req->flags & EVHTTP_REQ_OWN_CONNECTION); 
    evhttp_request_free(req); 
    ... 
} 
+0

謝謝,我有另一個問題,我使用bufferevent進行套接字通信,但我無法收到BEV_EVENT_EOF,現在我使用shutdown()函數,但它會導致錯誤。我怎樣才能正常關閉bufferevent。 \t evutil_socket_t fd = bufferevent_getfd(bev);關機(fd,1); – 2014-09-03 08:21:56

+0

不知道你是如何使用它,只是問另一個問題,我會看看我是否可以幫助。 – jfly 2014-09-03 08:58:58

+0

嗨,jfly,這是問題的網站。 http://stackoverflow.com/questions/25521992/how-to-close-bufferevent-normally – 2014-09-03 09:29:48