基于libevent的V2(evhttp),Linux和ARM,glibc2.3.4 C语言编写的轻量级http服务器:前言
我想在32位系统中使用evbuffer_add_file()担任大文件(超过2GB)。 所述的libevent用-D_FILE_OFFSET_BITS = 64标志编译。 下面是简化的代码:
int fd = -1;
if ((fd = open(path, O_RDONLY)) < 0) {
// error handling
}
struct stat st;
if (fstat(fd, &st) < 0) {
// error handling
}
struct evbuffer *buffer = evbuffer_new();
evbuffer_set_flags(buffer, EVBUFFER_FLAG_DRAINS_TO_FD); // force using system's sendfile
evbuffer_add_file(buffer, fd, 0, st.st_size);
evhttp_send_reply(req, 200, NULL, buffer);
evbuffer_free(buffer);
st.st_size具有正确的值,在这种情况下4913809524,但响应头的Content-Length有618842228.即使我Content-Length头设置到适当的数值文件传输在618842228停止值...
我错过或做错了什么? 是否有可能呢?
提前致谢
正如我在评论说,问题显然不在libevent的,但在系统的实施了sendfile。 因此只要解决办法,我发现使用evhttp_send_reply_来解决这个问题的方法(开始|块|完)系列函数:
struct chunk_req_state {
struct evhttp_request *req;
int fd;
long chunksize;
off_t filesize;
off_t offset;
};
static void
chunked_trickle_cb(evutil_socket_t fd, short events, void *arg)
{
struct evbuffer *evb = evbuffer_new();
struct chunk_req_state *state = arg;
struct timeval when = { 0, 0 };
ev_ssize_t read;
if (lseek(state->fd, state->offset, SEEK_SET) == -1) {
evbuffer_free(evb);
close(state->fd);
free(state);
return;
}
read = evbuffer_read(evb, state->fd, (ev_ssize_t) state->chunksize);
if (read == -1) {
evbuffer_free(evb);
evhttp_send_reply_end(state->req);
close(state->fd);
free(state);
return;
}
evhttp_send_reply_chunk(state->req, evb);
evbuffer_free(evb);
state->offset += read;
if (state->offset < state->filesize) {
// there's more data to send
event_base_once(ebase, -1, EV_TIMEOUT, chunked_trickle_cb, state, &when);
} else {
// reached the end
evhttp_send_reply_end(state->req);
close(state->fd);
free(state);
}
}
int fd = -1;
if ((fd = open(path, O_RDONLY)) < 0) {
// error handling
}
struct stat st;
if (fstat(fd, &st) < 0) {
// error handling
}
struct timeval when = { 0, 0 };
struct chunk_req_state *state = malloc(sizeof(struct chunk_req_state));
memset(state, 0, sizeof(struct chunk_req_state));
state->req = req;
state->fd = fd;
state->chunksize = 10*1024*1024;
state->filesize = st.st_size;
state->offset = 0;
// set Content-Length to prevent chunked transfer
char *length = NULL;
spprintf(&length, 0, "%lld", st.st_size);
evhttp_add_header(evhttp_request_get_output_headers(request->req), "Content-Length", length);
free(length);
evhttp_send_reply_start(request->req, 200, NULL);
event_base_once(ebase, -1, EV_TIMEOUT, chunked_trickle_cb, state, &when);