尝试从libuv服务器(简单)中创建logger,然后按照网上几乎找不到的示例 我确实设法写入文件但是当我尝试从代码中的某个不同位置写入日志时获得异常 这就是我所拥有的:
const char* logfile = "wsserver.log";
char buf[] = "Server Started!\n";
uv_fs_t open_req;
uv_fs_t write_req;
uv_fs_t close_req;
int resultFD;
void open_cb(uv_fs_t* req);
void write_cb(uv_fs_t* req);
void close_cb(uv_fs_t* req);
void open_cb(uv_fs_t* req) {
resultFD = req->result;
const uv_buf_t buf1 = uv_buf_init(&buf, sizeof(buf));
if (resultFD == -1) {
fprintf(stderr, "Error opening file: %s.\n",
uv_strerror(resultFD));
}
uv_fs_req_cleanup(req);
uv_fs_write(loop, &write_req, resultFD, &buf1, sizeof(buf1), -1, write_cb);
}
void write_cb(uv_fs_t* req) {
int result = req->result;
if (result == -1) {
fprintf(stderr, "Error writting data to file: %s.\n",
uv_strerror(result));
}
uv_fs_req_cleanup(req);
uv_fs_close(loop, &close_req, open_req.result, close_cb);
}
void close_cb(uv_fs_t* req) {
int result = req->result;
if (result == -1) {
fprintf(stderr, "Error closing file: %s.\n",
uv_strerror(result));
}
uv_fs_req_cleanup(req);
}
int main(int argc, char** argv)
{
int port = 8011;
loop = uv_default_loop();
if (server_start(port))
{
return 1;
}
int r = uv_fs_open(loop, &open_req, logfile, O_CREAT | O_APPEND, 0644, open_cb);
if (r) {
fprintf(stderr, "Error opening file: %s.\n",
uv_strerror(r));
}
uv_run(loop, UV_RUN_DEFAULT);
return 0;
}
此代码正常运行,它会创建文件并附加“Server Started!\ n”
字符串。
但问题是当我尝试从代码中的不同位置写入文件时,例如:
我试图在
libuv_httpparser_ws.exe!uv__get_osfhandle(int fd)文件中的第174行C:handle-inl.h
void after_read(uv_stream_t* handle, ssize_t nread, const uv_buf_t * buf) {
if (nread < 0) {
if (buf->base) {
free(buf->base);
}
uv_close((uv_handle_t*)handle, on_close);
return;
}
if (nread == 0) {
free(buf->base);
return;
}
_context* ctx = handle->data;
if (ctx->request->handshake == 0) {
//here you getting the request from the client
printf("buf->base %s\n", buf->base);
uv_fs_write(loop, &write_req, resultFD, buf->base, sizeof(buf->base), -1, write_cb); //<---HERE I TRY TO WRITE TO THE FILE WITHOUT SUCCESS
size_t np = http_parser_execute(ctx->parser, &settings, buf->base, nread);
int _http_errno =ctx->parser->http_errno;
const char * _errno = http_errno_description((enum http_errno)_http_errno);
int _upgrade = ctx->parser->upgrade;
free(buf->base);
if (np != nread) {
uv_shutdown_t* req;
req = (uv_shutdown_t*)malloc(sizeof *req);
uv_shutdown(req, handle, after_shutdown);
}
}
}
我做错了什么以及如何制作合适的简单记录器? 感谢
答案 0 :(得分:0)
在调用uv_fs_write之后你正在释放buf-> gt;但是uv_fs_write不会复制缓冲区的内容,因此在调用write回调之前内存必须保持有效。
我建议您使用阻止写入进行日志记录,直到它成为问题。然后可能会切换到使用UDP登录到远程服务器。