1

I am initializing a loop in libuv, but if I need to return after I initialized the loop but before I have called uv_run, how do I correctly clean up all memory and file descriptors? Here is my example code, loop being uv_loop_t* and server being uv_tcp_t*:

if (uv_loop_init(loop) < 0) {
    return -1;
}
if (uv_tcp_init(loop, server) < 0) {
    // What code here?
    return -1;
}
if (some_other_function() < 0) {
    // What code here?
    return -1;
}
uv_run(loop, UV_RUN_DEFAULT);

According to this question, I should stop, walk and run the loop, closing all the handles; but that assumes I'm already running the loop, which I'm not. I could just call uv_loop_close(loop), but that doesn't free the handles.

Sabrina Jewson
  • 1,478
  • 1
  • 10
  • 17

1 Answers1

1

As mentioned in the link, you need to do something like this;

uv_loop_init(&loop);
uv_tcp_init(&loop, &server);

uv_walk(&loop,
              [](uv_handle_t* handle, void* arg) {
                  printf("closing...%p\n", handle);
                  uv_close(handle, [](uv_handle_t* handle) {
                             printf("closed...%p\n", handle);
                             }
                          );
                  uv_run(&loop, UV_RUN_ONCE);
                  },
        NULL);
Kyrol
  • 3,475
  • 7
  • 34
  • 46
bertubezz
  • 361
  • 1
  • 8