Convert Figma logo to code with AI

libuv logolibuv

Cross-platform asynchronous I/O

24,692
3,630
24,692
180

Top Related Projects

108,341

Node.js JavaScript runtime ✨🐢🚀✨

27,713

A runtime for writing reliable asynchronous applications with Rust. Provides I/O, networking, scheduling, timers, ...

11,243

Event notification library

10,845

mimalloc is a compact general purpose allocator with excellent performance.

28,895

An open-source C++ library developed and used at Facebook.

Quick Overview

libuv is a multi-platform support library with a focus on asynchronous I/O. It was originally developed for Node.js but has since become a standalone project used by many other software systems. libuv provides core utilities for network and file system operations, as well as native OS functionality like processes and threads.

Pros

  • Cross-platform support for Windows, Linux, macOS, and other Unix-like systems
  • Efficient event loop implementation for high-performance asynchronous I/O
  • Comprehensive API covering networking, file system, and system-level operations
  • Active development and maintenance with a large community

Cons

  • Steep learning curve for developers new to asynchronous programming
  • Limited documentation for some advanced features
  • Potential for callback hell if not used carefully
  • Some platform-specific quirks may require additional handling

Code Examples

  1. Simple TCP echo server:
#include <uv.h>
#include <stdio.h>
#include <stdlib.h>

void echo_write(uv_write_t *req, int status) {
    if (status) {
        fprintf(stderr, "Write error %s\n", uv_strerror(status));
    }
    free(req);
}

void echo_read(uv_stream_t *client, ssize_t nread, const uv_buf_t *buf) {
    if (nread > 0) {
        uv_write_t *req = (uv_write_t *) malloc(sizeof(uv_write_t));
        uv_buf_t wrbuf = uv_buf_init(buf->base, nread);
        uv_write(req, client, &wrbuf, 1, echo_write);
    }
    if (nread < 0) {
        if (nread != UV_EOF)
            fprintf(stderr, "Read error %s\n", uv_err_name(nread));
        uv_close((uv_handle_t*) client, NULL);
    }
    free(buf->base);
}

void on_new_connection(uv_stream_t *server, int status) {
    if (status < 0) {
        fprintf(stderr, "New connection error %s\n", uv_strerror(status));
        return;
    }
    uv_tcp_t *client = (uv_tcp_t*) malloc(sizeof(uv_tcp_t));
    uv_tcp_init(uv_default_loop(), client);
    if (uv_accept(server, (uv_stream_t*) client) == 0) {
        uv_read_start((uv_stream_t*) client, alloc_buffer, echo_read);
    } else {
        uv_close((uv_handle_t*) client, NULL);
    }
}

int main() {
    uv_tcp_t server;
    uv_tcp_init(uv_default_loop(), &server);
    struct sockaddr_in addr;
    uv_ip4_addr("0.0.0.0", 7000, &addr);
    uv_tcp_bind(&server, (const struct sockaddr*)&addr, 0);
    int r = uv_listen((uv_stream_t*) &server, 128, on_new_connection);
    if (r) {
        fprintf(stderr, "Listen error %s\n", uv_strerror(r));
        return 1;
    }
    return uv_run(uv_default_loop(), UV_RUN_DEFAULT);
}
  1. File system operations:
#include <uv.h>
#include <stdio.h>

void on_read(uv_fs_t *req) {
    if (req->result < 0) {
        fprintf(stderr, "Read error: %s\n", uv_strerror(req->result));
    } else {
        uv_buf_t buf = *(uv_buf_t *)req->data;
        printf("File contents: %.*s", (int)req->result,

Competitor Comparisons

108,341

Node.js JavaScript runtime ✨🐢🚀✨

Pros of Node.js

  • Higher-level runtime environment, easier for developers to build applications
  • Extensive ecosystem with npm, providing access to numerous packages
  • Built-in support for asynchronous I/O operations

Cons of Node.js

  • Larger codebase and more complex architecture
  • Potentially higher memory usage due to V8 engine and additional features
  • Less flexibility for low-level system programming compared to libuv

Code Comparison

Node.js (JavaScript):

const http = require('http');

const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('Hello World\n');
});

server.listen(8080);

libuv (C):

#include <uv.h>

void on_connection(uv_stream_t *server, int status) {
    // Handle new connection
}

int main() {
    uv_tcp_t server;
    uv_tcp_init(uv_default_loop(), &server);
    // Set up and start the server
    return uv_run(uv_default_loop(), UV_RUN_DEFAULT);
}

The Node.js example demonstrates a higher-level API for creating an HTTP server, while the libuv example shows lower-level event loop and networking primitives.

27,713

A runtime for writing reliable asynchronous applications with Rust. Provides I/O, networking, scheduling, timers, ...

Pros of tokio

  • Written in Rust, offering memory safety and zero-cost abstractions
  • Provides a rich ecosystem of libraries and tools for async programming
  • Designed with modern concurrency patterns, making it easier to write efficient async code

Cons of tokio

  • Steeper learning curve, especially for developers new to Rust
  • Less mature and battle-tested compared to libuv's long history
  • May have more overhead for simple, single-threaded applications

Code Comparison

tokio:

#[tokio::main]
async fn main() {
    println!("Hello, world!");
    tokio::time::sleep(Duration::from_secs(1)).await;
}

libuv:

uv_loop_t *loop = uv_default_loop();
uv_timer_t timer;
uv_timer_init(loop, &timer);
uv_timer_start(&timer, timer_cb, 1000, 0);
uv_run(loop, UV_RUN_DEFAULT);

Both examples demonstrate a simple timer operation, showcasing the different approaches to asynchronous programming. tokio leverages Rust's async/await syntax for a more straightforward and readable code structure, while libuv uses a callback-based approach typical in C programming.

11,243

Event notification library

Pros of libevent

  • Mature and well-established library with a long history
  • Supports a wider range of platforms, including older systems
  • More flexible event model, allowing for fine-grained control

Cons of libevent

  • Less active development and slower release cycle
  • More complex API, requiring more boilerplate code
  • Limited built-in support for some modern networking features

Code Comparison

libevent example:

struct event_base *base = event_base_new();
struct event *ev = event_new(base, fd, EV_READ|EV_PERSIST, callback, NULL);
event_add(ev, NULL);
event_base_dispatch(base);

libuv example:

uv_loop_t *loop = uv_default_loop();
uv_poll_t poll_handle;
uv_poll_init(loop, &poll_handle, fd);
uv_poll_start(&poll_handle, UV_READABLE, callback);
uv_run(loop, UV_RUN_DEFAULT);

Both libraries provide event-driven I/O, but libuv offers a more streamlined API and better integration with Node.js. libevent has broader platform support and more flexibility, while libuv focuses on modern systems and provides additional features like thread pool and file system operations out of the box.

10,845

mimalloc is a compact general purpose allocator with excellent performance.

Pros of mimalloc

  • Highly optimized memory allocator focused on performance and low fragmentation
  • Designed for concurrent and parallel programs, with efficient thread-local caching
  • Easier to integrate into existing projects as a drop-in replacement for malloc

Cons of mimalloc

  • More specialized focus on memory allocation, lacking the broader event-driven I/O capabilities of libuv
  • May not provide as comprehensive cross-platform support as libuv for networking and file system operations

Code Comparison

mimalloc:

#include <mimalloc.h>

void* ptr = mi_malloc(sizeof(int));
mi_free(ptr);

libuv:

#include <uv.h>

uv_loop_t *loop = uv_default_loop();
uv_run(loop, UV_RUN_DEFAULT);
uv_loop_close(loop);

Summary

mimalloc is a high-performance memory allocator, while libuv is a multi-platform support library for asynchronous I/O. They serve different purposes, with mimalloc focusing on efficient memory management and libuv providing a broader set of tools for event-driven programming and cross-platform compatibility.

28,895

An open-source C++ library developed and used at Facebook.

Pros of Folly

  • Broader scope with a wide range of C++ utilities and components
  • Designed for high-performance, production-grade systems
  • Actively maintained by Facebook with frequent updates

Cons of Folly

  • Larger and more complex codebase, potentially steeper learning curve
  • May include unnecessary components for simpler projects
  • Primarily focused on C++, while libuv supports multiple languages

Code Comparison

Folly (C++):

#include <folly/Format.h>
#include <folly/FBString.h>

folly::fbstring result = folly::format("Hello, {}!", "World");

libuv (C):

#include <uv.h>

uv_loop_t *loop = uv_default_loop();
uv_tcp_t server;
uv_tcp_init(loop, &server);

Summary

Folly is a comprehensive C++ library with a wide range of utilities, while libuv focuses on asynchronous I/O operations. Folly is better suited for large-scale C++ projects, especially those requiring high performance. libuv is more specialized for cross-platform asynchronous I/O and is often used in Node.js-like environments. The choice between them depends on the specific project requirements and the preferred programming language.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

libuv

Overview

libuv is a multi-platform support library with a focus on asynchronous I/O. It was primarily developed for use by Node.js, but it's also used by Luvit, Julia, uvloop, and others.

Feature highlights

  • Full-featured event loop backed by epoll, kqueue, IOCP, event ports.

  • Asynchronous TCP and UDP sockets

  • Asynchronous DNS resolution

  • Asynchronous file and file system operations

  • File system events

  • ANSI escape code controlled TTY

  • IPC with socket sharing, using Unix domain sockets or named pipes (Windows)

  • Child processes

  • Thread pool

  • Signal handling

  • High resolution clock

  • Threading and synchronization primitives

Versioning

Starting with version 1.0.0 libuv follows the semantic versioning scheme. The API change and backwards compatibility rules are those indicated by SemVer. libuv will keep a stable ABI across major releases.

The ABI/API changes can be tracked here.

Licensing

libuv is licensed under the MIT license. Check the LICENSE and LICENSE-extra files.

The documentation is licensed under the CC BY 4.0 license. Check the LICENSE-docs file.

Community

Documentation

Official documentation

Located in the docs/ subdirectory. It uses the Sphinx framework, which makes it possible to build the documentation in multiple formats.

Show different supported building options:

$ make help

Build documentation as HTML:

$ make html

Build documentation as HTML and live reload it when it changes (this requires sphinx-autobuild to be installed and is only supported on Unix):

$ make livehtml

Build documentation as man pages:

$ make man

Build documentation as ePub:

$ make epub

NOTE: Windows users need to use make.bat instead of plain 'make'.

Documentation can be browsed online here.

The tests and benchmarks also serve as API specification and usage examples.

Other resources

  • LXJS 2012 talk — High-level introductory talk about libuv.
  • libuv-dox — Documenting types and methods of libuv, mostly by reading uv.h.
  • learnuv — Learn uv for fun and profit, a self guided workshop to libuv.

These resources are not handled by libuv maintainers and might be out of date. Please verify it before opening new issues.

Downloading

libuv can be downloaded either from the GitHub repository or from the downloads site.

Before verifying the git tags or signature files, importing the relevant keys is necessary. Key IDs are listed in the MAINTAINERS file, but are also available as git blob objects for easier use.

Importing a key the usual way:

$ gpg --keyserver pool.sks-keyservers.net --recv-keys AE9BC059

Importing a key from a git blob object:

$ git show pubkey-saghul | gpg --import

Verifying releases

Git tags are signed with the developer's key, they can be verified as follows:

$ git verify-tag v1.6.1

Starting with libuv 1.7.0, the tarballs stored in the downloads site are signed and an accompanying signature file sit alongside each. Once both the release tarball and the signature file are downloaded, the file can be verified as follows:

$ gpg --verify libuv-1.7.0.tar.gz.sign

Build Instructions

For UNIX-like platforms, including macOS, there are two build methods: autotools or CMake.

For Windows, CMake is the only supported build method and has the following prerequisites:

  • One of:
    • Visual C++ Build Tools
    • Visual Studio 2015 Update 3, all editions including the Community edition (remember to select "Common Tools for Visual C++ 2015" feature during installation).
    • Visual Studio 2017, any edition (including the Build Tools SKU). Required Components: "MSbuild", "VC++ 2017 v141 toolset" and one of the Windows SDKs (10 or 8.1).
  • Basic Unix tools required for some tests, Git for Windows includes Git Bash and tools which can be included in the global PATH.

To build with autotools:

$ sh autogen.sh
$ ./configure
$ make
$ make check
$ make install

To build with CMake:

$ mkdir -p build

$ (cd build && cmake .. -DBUILD_TESTING=ON) # generate project with tests
$ cmake --build build                       # add `-j <n>` with cmake >= 3.12

# Run tests:
$ (cd build && ctest -C Debug --output-on-failure)

# Or manually run tests:
$ build/uv_run_tests                        # shared library build
$ build/uv_run_tests_a                      # static library build

To cross-compile with CMake (unsupported but generally works):

$ cmake ../..                 \
  -DCMAKE_SYSTEM_NAME=Windows \
  -DCMAKE_SYSTEM_VERSION=6.1  \
  -DCMAKE_C_COMPILER=i686-w64-mingw32-gcc

Install with Homebrew

$ brew install --HEAD libuv

Note to OS X users:

Make sure that you specify the architecture you wish to build for in the "ARCHS" flag. You can specify more than one by delimiting with a space (e.g. "x86_64 i386").

Install with vcpkg

$ git clone https://github.com/microsoft/vcpkg.git
$ ./bootstrap-vcpkg.bat # for powershell
$ ./bootstrap-vcpkg.sh # for bash
$ ./vcpkg install libuv

Install with Conan

You can install pre-built binaries for libuv or build it from source using Conan. Use the following command:

conan install --requires="libuv/[*]" --build=missing

The libuv Conan recipe is kept up to date by Conan maintainers and community contributors. If the version is out of date, please create an issue or pull request on the ConanCenterIndex repository.

Running tests

Some tests are timing sensitive. Relaxing test timeouts may be necessary on slow or overloaded machines:

$ env UV_TEST_TIMEOUT_MULTIPLIER=2 build/uv_run_tests # 10s instead of 5s

Run one test

The list of all tests is in test/test-list.h.

This invocation will cause the test driver to fork and execute TEST_NAME in a child process:

$ build/uv_run_tests_a TEST_NAME

This invocation will cause the test driver to execute the test in the same process:

$ build/uv_run_tests_a TEST_NAME TEST_NAME

Debugging tools

When running the test from within the test driver process (build/uv_run_tests_a TEST_NAME TEST_NAME), tools like gdb and valgrind work normally.

When running the test from a child of the test driver process (build/uv_run_tests_a TEST_NAME), use these tools in a fork-aware manner.

Fork-aware gdb

Use the follow-fork-mode setting:

$ gdb --args build/uv_run_tests_a TEST_NAME

(gdb) set follow-fork-mode child
...
Fork-aware valgrind

Use the --trace-children=yes parameter:

$ valgrind --trace-children=yes -v --tool=memcheck --leak-check=full --track-origins=yes --leak-resolution=high --show-reachable=yes --log-file=memcheck-%p.log build/uv_run_tests_a TEST_NAME

Running benchmarks

See the section on running tests. The benchmark driver is ./uv_run_benchmarks_a and the benchmarks are listed in test/benchmark-list.h.

Supported Platforms

Check the SUPPORTED_PLATFORMS file.

-fno-strict-aliasing

It is recommended to turn on the -fno-strict-aliasing compiler flag in projects that use libuv. The use of ad hoc "inheritance" in the libuv API may not be safe in the presence of compiler optimizations that depend on strict aliasing.

MSVC does not have an equivalent flag but it also does not appear to need it at the time of writing (December 2019.)

AIX Notes

AIX compilation using IBM XL C/C++ requires version 12.1 or greater.

AIX support for filesystem events requires the non-default IBM bos.ahafs package to be installed. This package provides the AIX Event Infrastructure that is detected by autoconf. IBM documentation describes the package in more detail.

z/OS Notes

z/OS compilation requires ZOSLIB to be installed. When building with CMake, use the flag -DZOSLIB_DIR to specify the path to ZOSLIB:

$ (cd build && cmake .. -DBUILD_TESTING=ON -DZOSLIB_DIR=/path/to/zoslib)
$ cmake --build build

z/OS creates System V semaphores and message queues. These persist on the system after the process terminates unless the event loop is closed.

Use the ipcrm command to manually clear up System V resources.

Patches

See the guidelines for contributing.