我应该调用evhttp_request_free来释放http服务器中的资源吗?

时间:2014-09-03 03:42:42

标签: http free libevent

我使用libevent2.1.1编写一个简单的http服务器,我想我应该在evhttp_request中使用evhttp_request_free发布http_server_callback。但是当我运行它时,错误发生了。请告诉我为什么,以及我该做什么。

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;
}

提前致谢

1 个答案:

答案 0 :(得分: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);
    ...
}