【问题标题】:Should I call evhttp_request_free to release resource in http server?我应该调用 evhttp_request_free 来释放 http 服务器中的资源吗?
【发布时间】:2014-09-03 03:42:41
【问题描述】:

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

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

提前致谢

【问题讨论】:

  • 显示完整代码和错误详情。
  • 谢谢,jfly!我修改了问题,并发布了完整的代码和错误图。

标签: http free libevent


【解决方案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);
    ...
}

【讨论】:

  • 谢谢,我还有一个问题,我使用bufferevent进行套接字通信,但是我无法接收到BEV_EVENT_EOF,现在我使用了shutdown()函数,但是它会导致错误。我怎样才能正常关闭bufferevent。 evutil_socket_t fd = bufferevent_getfd(bev);关机(fd, 1);
  • 不知道你具体是怎么用的,再问一个问题,我看看能不能帮忙。
  • 嗨,jfly,这是问题站点。 stackoverflow.com/questions/25521992/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-18
  • 2010-09-08
  • 2011-03-21
  • 2017-04-01
  • 1970-01-01
相关资源
最近更新 更多