Search code examples
cexitnonblockinglibuv

libuv: how to gracefully exit application on an error?


I have an application which uses libuv library. it runs default loop:

uv_run(uv_default_loop());

How can the application be gracefully exited in case of a failure? Currently I am doing it like in the following example:

uv_tcp_t* tcp = malloc(sizeof(uv_tcp_t));
int r = uv_tcp_init(uv_default_loop(), tcp);

if (r) {
  free(tcp);
  uv_loop_delete(default_loop);
  exit(EXIT_FAILURE);
}

Should uv_loop_delete function be called? What does it do? Does it drop all pending callback functions? Does it close all currently opened TCP connections? Do I have to do it manually before exiting?

P.S.: Can't add the tag 'libuv' (less than 1500 reputation). Can somebody create and add it?


Solution

  • Declaration of uv_loop_delete is here and source code is here. It looks like this:

    void uv_loop_delete(uv_loop_t* loop) {
      uv_ares_destroy(loop, loop->channel);
      ev_loop_destroy(loop->ev);
    #if __linux__
      if (loop->inotify_fd == -1) return;
      ev_io_stop(loop->ev, &loop->inotify_read_watcher);
      close(loop->inotify_fd);
      loop->inotify_fd = -1;
    #endif
    #if HAVE_PORTS_FS
      if (loop->fs_fd != -1)
        close(loop->fs_fd);
    #endif
    }
    

    It will, effectively, clean every file descriptor it's possible to clean. It will close TCP connection, Inotify connections, Socket used to read events, Pipe fds, etc, etc.

    => Yes, this function will close everything you have opened through libuv.

    NB: Anyway, when your application exit, your Operating System will clean and close everything you have left open, without any mercy.