.
. RS \\$1 . nr rst2man-indent\\n[rst2man-indent-level] \\n[an-margin] . nr rst2man-indent-level +1 .rstReportMargin post:
.. . RE indent \\n[an-margin]
old: \\n[rst2man-indent\\n[rst2man-indent-level]]
.nr rst2man-indent-level -1 new: \\n[rst2man-indent\\n[rst2man-indent-level]]
..
UV_E2BIG argument list too long NINDENT NDENT 0.0
UV_EACCES permission denied NINDENT NDENT 0.0
UV_EADDRINUSE address already in use NINDENT NDENT 0.0
UV_EADDRNOTAVAIL address not available NINDENT NDENT 0.0
UV_EAFNOSUPPORT address family not supported NINDENT NDENT 0.0
UV_EAGAIN resource temporarily unavailable NINDENT NDENT 0.0
UV_EAI_ADDRFAMILY address family not supported NINDENT NDENT 0.0
UV_EAI_AGAIN temporary failure NINDENT NDENT 0.0
UV_EAI_BADFLAGS bad ai_flags value NINDENT NDENT 0.0
UV_EAI_BADHINTS invalid value for hints NINDENT NDENT 0.0
UV_EAI_CANCELED request canceled NINDENT NDENT 0.0
UV_EAI_FAIL permanent failure NINDENT NDENT 0.0
UV_EAI_FAMILY ai_family not supported NINDENT NDENT 0.0
UV_EAI_MEMORY out of memory NINDENT NDENT 0.0
UV_EAI_NODATA no address NINDENT NDENT 0.0
UV_EAI_NONAME unknown node or service NINDENT NDENT 0.0
UV_EAI_OVERFLOW argument buffer overflow NINDENT NDENT 0.0
UV_EAI_PROTOCOL resolved protocol is unknown NINDENT NDENT 0.0
UV_EAI_SERVICE service not available for socket type NINDENT NDENT 0.0
UV_EAI_SOCKTYPE socket type not supported NINDENT NDENT 0.0
UV_EALREADY connection already in progress NINDENT NDENT 0.0
UV_EBADF bad file descriptor NINDENT NDENT 0.0
UV_EBUSY resource busy or locked NINDENT NDENT 0.0
UV_ECANCELED operation canceled NINDENT NDENT 0.0
UV_ECHARSET invalid Unicode character NINDENT NDENT 0.0
UV_ECONNABORTED software caused connection abort NINDENT NDENT 0.0
UV_ECONNREFUSED connection refused NINDENT NDENT 0.0
UV_ECONNRESET connection reset by peer NINDENT NDENT 0.0
UV_EDESTADDRREQ destination address required NINDENT NDENT 0.0
UV_EEXIST file already exists NINDENT NDENT 0.0
UV_EFAULT bad address in system call argument NINDENT NDENT 0.0
UV_EFBIG file too large NINDENT NDENT 0.0
UV_EHOSTUNREACH host is unreachable NINDENT NDENT 0.0
UV_EINTR interrupted system call NINDENT NDENT 0.0
UV_EINVAL invalid argument NINDENT NDENT 0.0
UV_EIO i/o error NINDENT NDENT 0.0
UV_EISCONN socket is already connected NINDENT NDENT 0.0
UV_EISDIR illegal operation on a directory NINDENT NDENT 0.0
UV_ELOOP too many symbolic links encountered NINDENT NDENT 0.0
UV_EMFILE too many open files NINDENT NDENT 0.0
UV_EMSGSIZE message too long NINDENT NDENT 0.0
UV_ENAMETOOLONG name too long NINDENT NDENT 0.0
UV_ENETDOWN network is down NINDENT NDENT 0.0
UV_ENETUNREACH network is unreachable NINDENT NDENT 0.0
UV_ENFILE file table overflow NINDENT NDENT 0.0
UV_ENOBUFS no buffer space available NINDENT NDENT 0.0
UV_ENODEV no such device NINDENT NDENT 0.0
UV_ENOENT no such file or directory NINDENT NDENT 0.0
UV_ENOMEM not enough memory NINDENT NDENT 0.0
UV_ENONET machine is not on the network NINDENT NDENT 0.0
UV_ENOPROTOOPT protocol not available NINDENT NDENT 0.0
UV_ENOSPC no space left on device NINDENT NDENT 0.0
UV_ENOSYS function not implemented NINDENT NDENT 0.0
UV_ENOTCONN socket is not connected NINDENT NDENT 0.0
UV_ENOTDIR not a directory NINDENT NDENT 0.0
UV_ENOTEMPTY directory not empty NINDENT NDENT 0.0
UV_ENOTSOCK socket operation on non-socket NINDENT NDENT 0.0
UV_ENOTSUP operation not supported on socket NINDENT NDENT 0.0
UV_EPERM operation not permitted NINDENT NDENT 0.0
UV_EPIPE broken pipe NINDENT NDENT 0.0
UV_EPROTO protocol error NINDENT NDENT 0.0
UV_EPROTONOSUPPORT protocol not supported NINDENT NDENT 0.0
UV_EPROTOTYPE protocol wrong type for socket NINDENT NDENT 0.0
UV_ERANGE result too large NINDENT NDENT 0.0
UV_EROFS read-only file system NINDENT NDENT 0.0
UV_ESHUTDOWN cannot send after transport endpoint shutdown NINDENT NDENT 0.0
UV_ESPIPE invalid seek NINDENT NDENT 0.0
UV_ESRCH no such process NINDENT NDENT 0.0
UV_ETIMEDOUT connection timed out NINDENT NDENT 0.0
UV_ETXTBSY text file is busy NINDENT NDENT 0.0
UV_EXDEV cross-device link not permitted NINDENT NDENT 0.0
UV_UNKNOWN unknown error NINDENT NDENT 0.0
UV_EOF end of file NINDENT NDENT 0.0
UV_ENXIO no such device or address NINDENT NDENT 0.0
UV_EMLINK too many links NINDENT
UV_ERRNO_MAP(iter_macro) Macro that expands to a series of invocations of iter_macro for each of the error constants above. iter_macro is invoked with two arguments: the name of the error constant without the UV_ prefix, and the error message string literal. NINDENT NDENT 0.0
const char* uv_strerror(int err) Returns the error message for the given error code. Leaks a few bytes of memory when you call it with an unknown error code. NINDENT NDENT 0.0
char* uv_strerror_r(int err, char* buf, size_t buflen) Returns the error message for the given error code. The zero-terminated message is stored in the user-supplied buffer buf of at most buflen bytes. New in version 1.22.0. NINDENT NDENT 0.0
const char* uv_err_name(int err) Returns the error name for the given error code. Leaks a few bytes of memory when you call it with an unknown error code. NINDENT NDENT 0.0
char* uv_err_name_r(int err, char* buf, size_t buflen) Returns the error name for the given error code. The zero-terminated name is stored in the user-supplied buffer buf of at most buflen bytes. New in version 1.22.0. NINDENT NDENT 0.0
int uv_translate_sys_error(int sys_errno) Returns the libuv error code equivalent to the given platform dependent error code: POSIX error codes on Unix (the ones stored in errno), and Win32 error codes on Windows (those returned by GetLastError() or WSAGetLastError()). If sys_errno is already a libuv error, it is simply returned. Changed in version 1.10.0: function declared public. NINDENT
UV_VERSION_MAJOR libuv version\(aqs major number. NINDENT NDENT 0.0
UV_VERSION_MINOR libuv version\(aqs minor number. NINDENT NDENT 0.0
UV_VERSION_PATCH libuv version\(aqs patch number. NINDENT NDENT 0.0
UV_VERSION_IS_RELEASE Set to 1 to indicate a release version of libuv, 0 for a development snapshot. NINDENT NDENT 0.0
UV_VERSION_SUFFIX libuv version suffix. Certain development releases such as Release Candidates might have a suffix such as "rc". NINDENT NDENT 0.0
UV_VERSION_HEX Returns the libuv version packed into a single integer. 8 bits are used for each component, with the patch number stored in the 8 least significant bits. E.g. for libuv 1.2.3 this would be 0x010203. New in version 1.7.0. NINDENT
unsigned int uv_version(void) Returns \%UV_VERSION_HEX. NINDENT NDENT 0.0
const char* uv_version_string(void) Returns the libuv version number as a string. For non-release versions the version suffix is included. NINDENT
uv_loop_t Loop data type. NINDENT NDENT 0.0
uv_run_mode Mode used to run the loop with \%uv_run(). NDENT 7.0 NDENT 3.5
typedef enum { UV_RUN_DEFAULT = 0, UV_RUN_ONCE, UV_RUN_NOWAIT } uv_run_mode;NINDENT NINDENT NINDENT NDENT 0.0
void (*uv_walk_cb)(uv_handle_t* handle, void* arg) Type definition for callback passed to \%uv_walk(). NINDENT
void* uv_loop_t.data Space for user-defined arbitrary data. libuv does not use and does not touch this field. NINDENT
int uv_loop_init(uv_loop_t* loop) Initializes the given uv_loop_t structure. NINDENT NDENT 0.0
int uv_loop_configure(uv_loop_t* loop, uv_loop_option option, ...) New in version 1.0.2. Set additional loop options. You should normally call this before the first call to \%uv_run() unless mentioned otherwise. Returns 0 on success or a UV_E* error code on failure. Be prepared to handle UV_ENOSYS; it means the loop option is not supported by the platform. Supported options: NDENT 7.0
int uv_loop_close(uv_loop_t* loop) Releases all internal loop resources. Call this function only when the loop has finished executing and all open handles and requests have been closed, or it will return UV_EBUSY. After this function returns, the user can free the memory allocated for the loop. NINDENT NDENT 0.0
uv_loop_t* uv_default_loop(void) Returns the initialized default loop. It may return NULL in case of allocation failure. This function is just a convenient way for having a global loop throughout an application, the default loop is in no way different than the ones initialized with \%uv_loop_init(). As such, the default loop can (and should) be closed with \%uv_loop_close() so the resources associated with it are freed. WARNING: NDENT 7.0 NDENT 3.5 This function is not thread safe. NINDENT NINDENT NINDENT NDENT 0.0
int uv_run(uv_loop_t* loop, uv_run_mode mode) This function runs the event loop. It will act differently depending on the specified mode: NDENT 7.0
int uv_loop_alive(const uv_loop_t* loop) Returns non-zero if there are referenced active handles, active requests or closing handles in the loop. NINDENT NDENT 0.0
void uv_stop(uv_loop_t* loop) Stop the event loop, causing \%uv_run() to end as soon as possible. This will happen not sooner than the next loop iteration. If this function was called before blocking for i/o, the loop won\(aqt block for i/o on this iteration. NINDENT NDENT 0.0
size_t uv_loop_size(void) Returns the size of the uv_loop_t structure. Useful for FFI binding writers who don\(aqt want to know the structure layout. NINDENT NDENT 0.0
int uv_backend_fd(const uv_loop_t* loop) Get backend file descriptor. Only kqueue, epoll and event ports are supported. This can be used in conjunction with uv_run(loop, UV_RUN_NOWAIT) to poll in one thread and run the event loop\(aqs callbacks in another see test/test-embed.c for an example. NOTE: NDENT 7.0 NDENT 3.5 Embedding a kqueue fd in another kqueue pollset doesn\(aqt work on all platforms. It\(aqs not an error to add the fd but it never generates events. NINDENT NINDENT NINDENT NDENT 0.0
int uv_backend_timeout(const uv_loop_t* loop) Get the poll timeout. The return value is in milliseconds, or -1 for no timeout. NINDENT NDENT 0.0
uint64_t uv_now(const uv_loop_t* loop) Return the current timestamp in milliseconds. The timestamp is cached at the start of the event loop tick, see \%uv_update_time() for details and rationale. The timestamp increases monotonically from some arbitrary point in time. Don\(aqt make assumptions about the starting point, you will only get disappointed. NOTE: NDENT 7.0 NDENT 3.5 Use uv_hrtime() if you need sub-millisecond granularity. NINDENT NINDENT NINDENT NDENT 0.0
void uv_update_time(uv_loop_t* loop) Update the event loop\(aqs concept of "now". Libuv caches the current time at the start of the event loop tick in order to reduce the number of time-related system calls. You won\(aqt normally need to call this function unless you have callbacks that block the event loop for longer periods of time, where "longer" is somewhat subjective but probably on the order of a millisecond or more. NINDENT NDENT 0.0
void uv_walk(uv_loop_t* loop, uv_walk_cb walk_cb, void* arg) Walk the list of handles: walk_cb will be executed with the given arg. NINDENT NDENT 0.0
int uv_loop_fork(uv_loop_t* loop) New in version 1.12.0. Reinitialize any kernel state necessary in the child process after a \%fork(2) system call. Previously started watchers will continue to be started in the child process. It is necessary to explicitly call this function on every event loop created in the parent process that you plan to continue to use in the child, including the default loop (even if you don\(aqt continue to use it in the parent). This function must be called before calling \%uv_run() or any other API function using the loop in the child. Failure to do so will result in undefined behaviour, possibly including duplicate events delivered to both parent and child or aborting the child process. When possible, it is preferred to create a new loop in the child process instead of reusing a loop created in the parent. New loops created in the child process after the fork should not use this function. This function is not implemented on Windows, where it returns UV_ENOSYS. CAUTION: NDENT 7.0 NDENT 3.5 This function is experimental. It may contain bugs, and is subject to change or removal. API and ABI stability is not guaranteed. NINDENT NINDENT NOTE: NDENT 7.0 NDENT 3.5 On Mac OS X, if directory FS event handles were in use in the parent process for any event loop, the child process will no longer be able to use the most efficient FSEvent implementation. Instead, uses of directory FS event handles in the child will fall back to the same implementation used for files and on other kqueue-based systems. NINDENT NINDENT CAUTION: NDENT 7.0 NDENT 3.5 On AIX and SunOS, FS event handles that were already started in the parent process at the time of forking will not deliver events in the child process; they must be closed and restarted. On all other platforms, they will continue to work normally without any further intervention. NINDENT NINDENT CAUTION: NDENT 7.0 NDENT 3.5 Any previous value returned from \%uv_backend_fd() is now invalid. That function must be called again to determine the correct backend file descriptor. NINDENT NINDENT NINDENT NDENT 0.0
void* uv_loop_get_data(const uv_loop_t* loop) Returns loop->data. New in version 1.19.0. NINDENT NDENT 0.0
void* uv_loop_set_data(uv_loop_t* loop, void* data) Sets loop->data to data. New in version 1.19.0. NINDENT
uv_handle_t The base libuv handle type. NINDENT NDENT 0.0
uv_handle_type The kind of the libuv handle. NDENT 7.0 NDENT 3.5
typedef enum { UV_UNKNOWN_HANDLE = 0, UV_ASYNC, UV_CHECK, UV_FS_EVENT, UV_FS_POLL, UV_HANDLE, UV_IDLE, UV_NAMED_PIPE, UV_POLL, UV_PREPARE, UV_PROCESS, UV_STREAM, UV_TCP, UV_TIMER, UV_TTY, UV_UDP, UV_SIGNAL, UV_FILE, UV_HANDLE_TYPE_MAX } uv_handle_type;NINDENT NINDENT NINDENT NDENT 0.0
uv_any_handle Union of all handle types. NINDENT NDENT 0.0
void (*uv_alloc_cb)(uv_handle_t* handle, size_t suggested_size, uv_buf_t* buf) Type definition for callback passed to uv_read_start() and uv_udp_recv_start(). The user must allocate memory and fill the supplied uv_buf_t structure. If NULL is assigned as the buffer\(aqs base or 0 as its length, a UV_ENOBUFS error will be triggered in the uv_udp_recv_cb or the uv_read_cb callback. Each buffer is used only once and the user is responsible for freeing it in the uv_udp_recv_cb or the uv_read_cb callback. A suggested size (65536 at the moment in most cases) is provided, but it\(aqs just an indication, not related in any way to the pending data to be read. The user is free to allocate the amount of memory they decide. As an example, applications with custom allocation schemes such as using freelists, allocation pools or slab based allocators may decide to use a different size which matches the memory chunks they already have. Example: NDENT 7.0 NDENT 3.5
static void my_alloc_cb(uv_handle_t* handle, size_t suggested_size, uv_buf_t* buf) { buf->base = malloc(suggested_size); buf->len = suggested_size; }NINDENT NINDENT NINDENT NDENT 0.0
void (*uv_close_cb)(uv_handle_t* handle) Type definition for callback passed to \%uv_close(). NINDENT
uv_loop_t* uv_handle_t.loop Pointer to the uv_loop_t the handle is running on. Readonly. NINDENT NDENT 0.0
uv_handle_type uv_handle_t.type The \%uv_handle_type, indicating the type of the underlying handle. Readonly. NINDENT NDENT 0.0
void* uv_handle_t.data Space for user-defined arbitrary data. libuv does not use this field. NINDENT
UV_HANDLE_TYPE_MAP(iter_macro) Macro that expands to a series of invocations of iter_macro for each of the handle types. iter_macro is invoked with two arguments: the name of the uv_handle_type element without the UV_ prefix, and the name of the corresponding structure type without the uv_ prefix and _t suffix. NINDENT NDENT 0.0
int uv_is_active(const uv_handle_t* handle) Returns non-zero if the handle is active, zero if it\(aqs inactive. What "active" means depends on the type of handle: NDENT 7.0
int uv_is_closing(const uv_handle_t* handle) Returns non-zero if the handle is closing or closed, zero otherwise. NOTE: NDENT 7.0 NDENT 3.5 This function should only be used between the initialization of the handle and the arrival of the close callback. NINDENT NINDENT NINDENT NDENT 0.0
void uv_close(uv_handle_t* handle, uv_close_cb close_cb) Request handle to be closed. close_cb will be called asynchronously after this call. This MUST be called on each handle before memory is released. Moreover, the memory can only be released in close_cb or after it has returned. Handles that wrap file descriptors are closed immediately but close_cb will still be deferred to the next iteration of the event loop. It gives you a chance to free up any resources associated with the handle. In-progress requests, like uv_connect_t or uv_write_t, are cancelled and have their callbacks called asynchronously with status=UV_ECANCELED. NINDENT NDENT 0.0
void uv_ref(uv_handle_t* handle) Reference the given handle. References are idempotent, that is, if a handle is already referenced calling this function again will have no effect. See \%Reference counting. NINDENT NDENT 0.0
void uv_unref(uv_handle_t* handle) Un-reference the given handle. References are idempotent, that is, if a handle is not referenced calling this function again will have no effect. See \%Reference counting. NINDENT NDENT 0.0
int uv_has_ref(const uv_handle_t* handle) Returns non-zero if the handle referenced, zero otherwise. See \%Reference counting. NINDENT NDENT 0.0
size_t uv_handle_size(uv_handle_type type) Returns the size of the given handle type. Useful for FFI binding writers who don\(aqt want to know the structure layout. NINDENT
int uv_send_buffer_size(uv_handle_t* handle, int* value) Gets or sets the size of the send buffer that the operating system uses for the socket. If *value == 0, then it will set *value to the current send buffer size. If *value > 0 then it will use *value to set the new send buffer size. On success, zero is returned. On error, a negative result is returned. This function works for TCP, pipe and UDP handles on Unix and for TCP and UDP handles on Windows. NOTE: NDENT 7.0 NDENT 3.5 Linux will set double the size and return double the size of the original set value. NINDENT NINDENT NINDENT NDENT 0.0
int uv_recv_buffer_size(uv_handle_t* handle, int* value) Gets or sets the size of the receive buffer that the operating system uses for the socket. If *value == 0, then it will set *value to the current receive buffer size. If *value > 0 then it will use *value to set the new receive buffer size. On success, zero is returned. On error, a negative result is returned. This function works for TCP, pipe and UDP handles on Unix and for TCP and UDP handles on Windows. NOTE: NDENT 7.0 NDENT 3.5 Linux will set double the size and return double the size of the original set value. NINDENT NINDENT NINDENT NDENT 0.0
int uv_fileno(const uv_handle_t* handle, uv_os_fd_t* fd) Gets the platform dependent file descriptor equivalent. The following handles are supported: TCP, pipes, TTY, UDP and poll. Passing any other handle type will fail with UV_EINVAL. If a handle doesn\(aqt have an attached file descriptor yet or the handle itself has been closed, this function will return UV_EBADF. WARNING: NDENT 7.0 NDENT 3.5 Be very careful when using this function. libuv assumes it\(aqs in control of the file descriptor so any change to it may lead to malfunction. NINDENT NINDENT NINDENT NDENT 0.0
uv_loop_t* uv_handle_get_loop(const uv_handle_t* handle) Returns handle->loop. New in version 1.19.0. NINDENT NDENT 0.0
void* uv_handle_get_data(const uv_handle_t* handle) Returns handle->data. New in version 1.19.0. NINDENT NDENT 0.0
void* uv_handle_set_data(uv_handle_t* handle, void* data) Sets handle->data to data. New in version 1.19.0. NINDENT NDENT 0.0
uv_handle_type uv_handle_get_type(const uv_handle_t* handle) Returns handle->type. New in version 1.19.0. NINDENT NDENT 0.0
const char* uv_handle_type_name(uv_handle_type type) Returns the name for the equivalent struct for a given handle type, e.g. "pipe" (as in uv_pipe_t) for UV_NAMED_PIPE. If no such handle type exists, this returns NULL. New in version 1.19.0. NINDENT
uv_req_t The base libuv request structure. NINDENT NDENT 0.0
uv_any_req Union of all request types. NINDENT
void* uv_req_t.data Space for user-defined arbitrary data. libuv does not use this field. NINDENT NDENT 0.0
uv_req_type uv_req_t.type Indicated the type of request. Readonly. NDENT 7.0 NDENT 3.5
typedef enum { UV_UNKNOWN_REQ = 0, UV_REQ, UV_CONNECT, UV_WRITE, UV_SHUTDOWN, UV_UDP_SEND, UV_FS, UV_WORK, UV_GETADDRINFO, UV_GETNAMEINFO, UV_REQ_TYPE_MAX, } uv_req_type;NINDENT NINDENT NINDENT
UV_REQ_TYPE_MAP(iter_macro) Macro that expands to a series of invocations of iter_macro for each of the request types. iter_macro is invoked with two arguments: the name of the uv_req_type element without the UV_ prefix, and the name of the corresponding structure type without the uv_ prefix and _t suffix. NINDENT NDENT 0.0
int uv_cancel(uv_req_t* req) Cancel a pending request. Fails if the request is executing or has finished executing. Returns 0 on success, or an error code < 0 on failure. Only cancellation of uv_fs_t, uv_getaddrinfo_t, uv_getnameinfo_t, uv_random_t and uv_work_t requests is currently supported. Cancelled requests have their callbacks invoked some time in the future. It\(aqs not safe to free the memory associated with the request until the callback is called. Here is how cancellation is reported to the callback: NDENT 7.0
size_t uv_req_size(uv_req_type type) Returns the size of the given request type. Useful for FFI binding writers who don\(aqt want to know the structure layout. NINDENT NDENT 0.0
void* uv_req_get_data(const uv_req_t* req) Returns req->data. New in version 1.19.0. NINDENT NDENT 0.0
void* uv_req_set_data(uv_req_t* req, void* data) Sets req->data to data. New in version 1.19.0. NINDENT NDENT 0.0
uv_req_type uv_req_get_type(const uv_req_t* req) Returns req->type. New in version 1.19.0. NINDENT NDENT 0.0
const char* uv_req_type_name(uv_req_type type) Returns the name for the equivalent struct for a given request type, e.g. "connect" (as in uv_connect_t) for UV_CONNECT. If no such request type exists, this returns NULL. New in version 1.19.0. NINDENT
uv_timer_t Timer handle type. NINDENT NDENT 0.0
void (*uv_timer_cb)(uv_timer_t* handle) Type definition for callback passed to \%uv_timer_start(). NINDENT
int uv_timer_init(uv_loop_t* loop, uv_timer_t* handle) Initialize the handle. NINDENT NDENT 0.0
int uv_timer_start(uv_timer_t* handle, uv_timer_cb cb, uint64_t timeout, uint64_t repeat) Start the timer. timeout and repeat are in milliseconds. If timeout is zero, the callback fires on the next event loop iteration. If repeat is non-zero, the callback fires first after timeout milliseconds and then repeatedly after repeat milliseconds. NOTE: NDENT 7.0 NDENT 3.5 Does not update the event loop\(aqs concept of "now". See uv_update_time() for more information. If the timer is already active, it is simply updated. NINDENT NINDENT NINDENT NDENT 0.0
int uv_timer_stop(uv_timer_t* handle) Stop the timer, the callback will not be called anymore. NINDENT NDENT 0.0
int uv_timer_again(uv_timer_t* handle) Stop the timer, and if it is repeating restart it using the repeat value as the timeout. If the timer has never been started before it returns UV_EINVAL. NINDENT NDENT 0.0
void uv_timer_set_repeat(uv_timer_t* handle, uint64_t repeat) Set the repeat interval value in milliseconds. The timer will be scheduled to run on the given interval, regardless of the callback execution duration, and will follow normal timer semantics in the case of a time-slice overrun. For example, if a 50ms repeating timer first runs for 17ms, it will be scheduled to run again 33ms later. If other tasks consume more than the 33ms following the first timer callback, then the callback will run as soon as possible. NOTE: NDENT 7.0 NDENT 3.5 If the repeat value is set from a timer callback it does not immediately take effect. If the timer was non-repeating before, it will have been stopped. If it was repeating, then the old repeat value will have been used to schedule the next timeout. NINDENT NINDENT NINDENT NDENT 0.0
uint64_t uv_timer_get_repeat(const uv_timer_t* handle) Get the timer repeat value. NINDENT SEE ALSO: NDENT 0.0 NDENT 3.5 The uv_handle_t API functions also apply. NINDENT NINDENT
uv_prepare_t Prepare handle type. NINDENT NDENT 0.0
void (*uv_prepare_cb)(uv_prepare_t* handle) Type definition for callback passed to \%uv_prepare_start(). NINDENT
int uv_prepare_init(uv_loop_t* loop, uv_prepare_t* prepare) Initialize the handle. This function always succeeds. NDENT 7.0
Returns 0 NINDENT NINDENT NDENT 0.0
int uv_prepare_start(uv_prepare_t* prepare, uv_prepare_cb cb) Start the handle with the given callback. This function always succeeds, except when cb is NULL. NDENT 7.0
Returns 0 on success, or UV_EINVAL when cb == NULL. NINDENT NINDENT NDENT 0.0
int uv_prepare_stop(uv_prepare_t* prepare) Stop the handle, the callback will no longer be called. This function always succeeds. NDENT 7.0
Returns 0 NINDENT NINDENT SEE ALSO: NDENT 0.0 NDENT 3.5 The uv_handle_t API functions also apply. NINDENT NINDENT
uv_check_t Check handle type. NINDENT NDENT 0.0
void (*uv_check_cb)(uv_check_t* handle) Type definition for callback passed to \%uv_check_start(). NINDENT
int uv_check_init(uv_loop_t* loop, uv_check_t* check) Initialize the handle. This function always succeeds. NDENT 7.0
Returns 0 NINDENT NINDENT NDENT 0.0
int uv_check_start(uv_check_t* check, uv_check_cb cb) Start the handle with the given callback. This function always succeeds, except when cb is NULL. NDENT 7.0
Returns 0 on success, or UV_EINVAL when cb == NULL. NINDENT NINDENT NDENT 0.0
int uv_check_stop(uv_check_t* check) Stop the handle, the callback will no longer be called. This function always succeeds. NDENT 7.0
Returns 0 NINDENT NINDENT SEE ALSO: NDENT 0.0 NDENT 3.5 The uv_handle_t API functions also apply. NINDENT NINDENT
uv_idle_t Idle handle type. NINDENT NDENT 0.0
void (*uv_idle_cb)(uv_idle_t* handle) Type definition for callback passed to \%uv_idle_start(). NINDENT
int uv_idle_init(uv_loop_t* loop, uv_idle_t* idle) Initialize the handle. This function always succeeds. NDENT 7.0
Returns 0 NINDENT NINDENT NDENT 0.0
int uv_idle_start(uv_idle_t* idle, uv_idle_cb cb) Start the handle with the given callback. This function always succeeds, except when cb is NULL. NDENT 7.0
Returns 0 on success, or UV_EINVAL when cb == NULL. NINDENT NINDENT NDENT 0.0
int uv_idle_stop(uv_idle_t* idle) Stop the handle, the callback will no longer be called. This function always succeeds. NDENT 7.0
Returns 0 NINDENT NINDENT SEE ALSO: NDENT 0.0 NDENT 3.5 The uv_handle_t API functions also apply. NINDENT NINDENT
uv_async_t Async handle type. NINDENT NDENT 0.0
void (*uv_async_cb)(uv_async_t* handle) Type definition for callback passed to \%uv_async_init(). NINDENT
int uv_async_init(uv_loop_t* loop, uv_async_t* async, uv_async_cb async_cb) Initialize the handle. A NULL callback is allowed. NDENT 7.0
Returns 0 on success, or an error code < 0 on failure. NINDENT NOTE: NDENT 7.0 NDENT 3.5 Unlike other handle initialization functions, it immediately starts the handle. NINDENT NINDENT NINDENT NDENT 0.0
int uv_async_send(uv_async_t* async) Wake up the event loop and call the async handle\(aqs callback. NDENT 7.0
Returns 0 on success, or an error code < 0 on failure. NINDENT NOTE: NDENT 7.0 NDENT 3.5 It\(aqs safe to call this function from any thread. The callback will be called on the loop thread. NINDENT NINDENT NOTE: NDENT 7.0 NDENT 3.5 \%uv_async_send() is \%async-signal-safe. It\(aqs safe to call this function from a signal handler. NINDENT NINDENT WARNING: NDENT 7.0 NDENT 3.5 libuv will coalesce calls to \%uv_async_send(), that is, not every call to it will yield an execution of the callback. For example: if \%uv_async_send() is called 5 times in a row before the callback is called, the callback will only be called once. If \%uv_async_send() is called again after the callback was called, it will be called again. NINDENT NINDENT NINDENT SEE ALSO: NDENT 0.0 NDENT 3.5 The uv_handle_t API functions also apply. NINDENT NINDENT
uv_poll_t Poll handle type. NINDENT NDENT 0.0
void (*uv_poll_cb)(uv_poll_t* handle, int status, int events) Type definition for callback passed to \%uv_poll_start(). NINDENT NDENT 0.0
uv_poll_event Poll event types NDENT 7.0 NDENT 3.5
enum uv_poll_event { UV_READABLE = 1, UV_WRITABLE = 2, UV_DISCONNECT = 4, UV_PRIORITIZED = 8 };NINDENT NINDENT NINDENT
int uv_poll_init(uv_loop_t* loop, uv_poll_t* handle, int fd) Initialize the handle using a file descriptor. Changed in version 1.2.2: the file descriptor is set to non-blocking mode. NINDENT NDENT 0.0
int uv_poll_init_socket(uv_loop_t* loop, uv_poll_t* handle, uv_os_sock_t socket) Initialize the handle using a socket descriptor. On Unix this is identical to \%uv_poll_init(). On windows it takes a SOCKET handle. Changed in version 1.2.2: the socket is set to non-blocking mode. NINDENT NDENT 0.0
int uv_poll_start(uv_poll_t* handle, int events, uv_poll_cb cb) Starts polling the file descriptor. events is a bitmask made up of UV_READABLE, UV_WRITABLE, UV_PRIORITIZED and UV_DISCONNECT. As soon as an event is detected the callback will be called with status set to 0, and the detected events set on the events field. The UV_PRIORITIZED event is used to watch for sysfs interrupts or TCP out-of-band messages. The UV_DISCONNECT event is optional in the sense that it may not be reported and the user is free to ignore it, but it can help optimize the shutdown path because an extra read or write call might be avoided. If an error happens while polling, status will be < 0 and corresponds with one of the UV_E* error codes (see errors). The user should not close the socket while the handle is active. If the user does that anyway, the callback may be called reporting an error status, but this is not guaranteed. NOTE: NDENT 7.0 NDENT 3.5 Calling \%uv_poll_start() on a handle that is already active is fine. Doing so will update the events mask that is being watched for. NINDENT NINDENT NOTE: NDENT 7.0 NDENT 3.5 Though UV_DISCONNECT can be set, it is unsupported on AIX and as such will not be set on the events field in the callback. NINDENT NINDENT Changed in version 1.9.0: Added the UV_DISCONNECT event. Changed in version 1.14.0: Added the UV_PRIORITIZED event. NINDENT NDENT 0.0
int uv_poll_stop(uv_poll_t* poll) Stop polling the file descriptor, the callback will no longer be called. NINDENT SEE ALSO: NDENT 0.0 NDENT 3.5 The uv_handle_t API functions also apply. NINDENT NINDENT
uv_signal_t Signal handle type. NINDENT NDENT 0.0
void (*uv_signal_cb)(uv_signal_t* handle, int signum) Type definition for callback passed to \%uv_signal_start(). NINDENT
int uv_signal_t.signum Signal being monitored by this handle. Readonly. NINDENT SEE ALSO: NDENT 0.0 NDENT 3.5 The uv_handle_t members also apply. NINDENT NINDENT
int uv_signal_init(uv_loop_t* loop, uv_signal_t* signal) Initialize the handle. NINDENT NDENT 0.0
int uv_signal_start(uv_signal_t* signal, uv_signal_cb cb, int signum) Start the handle with the given callback, watching for the given signal. NINDENT NDENT 0.0
int uv_signal_start_oneshot(uv_signal_t* signal, uv_signal_cb cb, int signum) New in version 1.12.0. Same functionality as \%uv_signal_start() but the signal handler is reset the moment the signal is received. NINDENT NDENT 0.0
int uv_signal_stop(uv_signal_t* signal) Stop the handle, the callback will no longer be called. NINDENT SEE ALSO: NDENT 0.0 NDENT 3.5 The uv_handle_t API functions also apply. NINDENT NINDENT
uv_process_t Process handle type. NINDENT NDENT 0.0
uv_process_options_t Options for spawning the process (passed to \%uv_spawn(). NDENT 7.0 NDENT 3.5
typedef struct uv_process_options_s { uv_exit_cb exit_cb; const char* file; char** args; char** env; const char* cwd; unsigned int flags; int stdio_count; uv_stdio_container_t* stdio; uv_uid_t uid; uv_gid_t gid; } uv_process_options_t;NINDENT NINDENT NINDENT NDENT 0.0
void (*uv_exit_cb)(uv_process_t*, int64_t exit_status, int term_signal) Type definition for callback passed in \%uv_process_options_t which will indicate the exit status and the signal that caused the process to terminate, if any. NINDENT NDENT 0.0
uv_process_flags Flags to be set on the flags field of \%uv_process_options_t. NDENT 7.0 NDENT 3.5
enum uv_process_flags { /* * Set the child process\(aq user id. */ UV_PROCESS_SETUID = (1 << 0), /* * Set the child process\(aq group id. */ UV_PROCESS_SETGID = (1 << 1), /* * Do not wrap any arguments in quotes, or perform any other escaping, when * converting the argument list into a command line string. This option is * only meaningful on Windows systems. On Unix it is silently ignored. */ UV_PROCESS_WINDOWS_VERBATIM_ARGUMENTS = (1 << 2), /* * Spawn the child process in a detached state - this will make it a process * group leader, and will effectively enable the child to keep running after * the parent exits. Note that the child process will still keep the * parent\(aqs event loop alive unless the parent process calls uv_unref() on * the child\(aqs process handle. */ UV_PROCESS_DETACHED = (1 << 3), /* * Hide the subprocess window that would normally be created. This option is * only meaningful on Windows systems. On Unix it is silently ignored. */ UV_PROCESS_WINDOWS_HIDE = (1 << 4), /* * Hide the subprocess console window that would normally be created. This * option is only meaningful on Windows systems. On Unix it is silently * ignored. */ UV_PROCESS_WINDOWS_HIDE_CONSOLE = (1 << 5), /* * Hide the subprocess GUI window that would normally be created. This * option is only meaningful on Windows systems. On Unix it is silently * ignored. */ UV_PROCESS_WINDOWS_HIDE_GUI = (1 << 6) };NINDENT NINDENT NINDENT NDENT 0.0
uv_stdio_container_t Container for each stdio handle or fd passed to a child process. NDENT 7.0 NDENT 3.5
typedef struct uv_stdio_container_s { uv_stdio_flags flags; union { uv_stream_t* stream; int fd; } data; } uv_stdio_container_t;NINDENT NINDENT NINDENT NDENT 0.0
uv_stdio_flags Flags specifying how a stdio should be transmitted to the child process. NDENT 7.0 NDENT 3.5
typedef enum { UV_IGNORE = 0x00, UV_CREATE_PIPE = 0x01, UV_INHERIT_FD = 0x02, UV_INHERIT_STREAM = 0x04, /* * When UV_CREATE_PIPE is specified, UV_READABLE_PIPE and UV_WRITABLE_PIPE * determine the direction of flow, from the child process\(aq perspective. Both * flags may be specified to create a duplex data stream. */ UV_READABLE_PIPE = 0x10, UV_WRITABLE_PIPE = 0x20 /* * Open the child pipe handle in overlapped mode on Windows. * On Unix it is silently ignored. */ UV_OVERLAPPED_PIPE = 0x40 } uv_stdio_flags;NINDENT NINDENT NINDENT
uv_process_t.pid The PID of the spawned process. It\(aqs set after calling \%uv_spawn(). NINDENT NOTE: NDENT 0.0 NDENT 3.5 The uv_handle_t members also apply. NINDENT NINDENT NDENT 0.0
uv_process_options_t.exit_cb Callback called after the process exits. NINDENT NDENT 0.0
uv_process_options_t.file Path pointing to the program to be executed. NINDENT NDENT 0.0
uv_process_options_t.args Command line arguments. args[0] should be the path to the program. On Windows this uses CreateProcess which concatenates the arguments into a string this can cause some strange errors. See the UV_PROCESS_WINDOWS_VERBATIM_ARGUMENTS flag on \%uv_process_flags. NINDENT NDENT 0.0
uv_process_options_t.env Environment for the new process. If NULL the parents environment is used. NINDENT NDENT 0.0
uv_process_options_t.cwd Current working directory for the subprocess. NINDENT NDENT 0.0
uv_process_options_t.flags Various flags that control how \%uv_spawn() behaves. See \%uv_process_flags. NINDENT NDENT 0.0
uv_process_options_t.stdio_count NINDENT NDENT 0.0
uv_process_options_t.stdio The stdio field points to an array of \%uv_stdio_container_t structs that describe the file descriptors that will be made available to the child process. The convention is that stdio[0] points to stdin, fd 1 is used for stdout, and fd 2 is stderr. NOTE: NDENT 7.0 NDENT 3.5 On Windows file descriptors greater than 2 are available to the child process only if the child processes uses the MSVCRT runtime. NINDENT NINDENT NINDENT NDENT 0.0
uv_process_options_t.uid NINDENT NDENT 0.0
uv_process_options_t.gid Libuv can change the child process\(aq user/group id. This happens only when the appropriate bits are set in the flags fields. NOTE: NDENT 7.0 NDENT 3.5 This is not supported on Windows, \%uv_spawn() will fail and set the error to UV_ENOTSUP. NINDENT NINDENT NINDENT NDENT 0.0
uv_stdio_container_t.flags Flags specifying how the stdio container should be passed to the child. See \%uv_stdio_flags. NINDENT NDENT 0.0
uv_stdio_container_t.data Union containing either the stream or fd to be passed on to the child process. NINDENT
void uv_disable_stdio_inheritance(void) Disables inheritance for file descriptors / handles that this process inherited from its parent. The effect is that child processes spawned by this process don\(aqt accidentally inherit these handles. It is recommended to call this function as early in your program as possible, before the inherited file descriptors can be closed or duplicated. NOTE: NDENT 7.0 NDENT 3.5 This function works on a best-effort basis: there is no guarantee that libuv can discover all file descriptors that were inherited. In general it does a better job on Windows than it does on Unix. NINDENT NINDENT NINDENT NDENT 0.0
int uv_spawn(uv_loop_t* loop, uv_process_t* handle, const uv_process_options_t* options) Initializes the process handle and starts the process. If the process is successfully spawned, this function will return 0. Otherwise, the negative error code corresponding to the reason it couldn\(aqt spawn is returned. Possible reasons for failing to spawn would include (but not be limited to) the file to execute not existing, not having permissions to use the setuid or setgid specified, or not having enough memory to allocate for the new process. Changed in version 1.24.0: Added UV_PROCESS_WINDOWS_HIDE_CONSOLE and UV_PROCESS_WINDOWS_HIDE_GUI flags. NINDENT NDENT 0.0
int uv_process_kill(uv_process_t* handle, int signum) Sends the specified signal to the given process handle. Check the documentation on signal for signal support, specially on Windows. NINDENT NDENT 0.0
int uv_kill(int pid, int signum) Sends the specified signal to the given PID. Check the documentation on signal for signal support, specially on Windows. NINDENT NDENT 0.0
uv_pid_t uv_process_get_pid(const uv_process_t* handle) Returns handle->pid. New in version 1.19.0. NINDENT SEE ALSO: NDENT 0.0 NDENT 3.5 The uv_handle_t API functions also apply. NINDENT NINDENT
uv_stream_t Stream handle type. NINDENT NDENT 0.0
uv_connect_t Connect request type. NINDENT NDENT 0.0
uv_shutdown_t Shutdown request type. NINDENT NDENT 0.0
uv_write_t Write request type. Careful attention must be paid when reusing objects of this type. When a stream is in non-blocking mode, write requests sent with uv_write will be queued. Reusing objects at this point is undefined behaviour. It is safe to reuse the uv_write_t object only after the callback passed to uv_write is fired. NINDENT NDENT 0.0
void (*uv_read_cb)(uv_stream_t* stream, ssize_t nread, const uv_buf_t* buf) Callback called when data was read on a stream. nread is > 0 if there is data available or < 0 on error. When we\(aqve reached EOF, nread will be set to UV_EOF. When nread < 0, the buf parameter might not point to a valid buffer; in that case buf.len and buf.base are both set to 0. NOTE: NDENT 7.0 NDENT 3.5 nread might be 0, which does not indicate an error or EOF. This is equivalent to EAGAIN or EWOULDBLOCK under read(2). NINDENT NINDENT The callee is responsible for stopping/closing the stream when an error happens by calling \%uv_read_stop() or uv_close(). Trying to read from the stream again is undefined. The callee is responsible for freeing the buffer, libuv does not reuse it. The buffer may be a null buffer (where buf->base == NULL and buf->len == 0) on error. NINDENT NDENT 0.0
void (*uv_write_cb)(uv_write_t* req, int status) Callback called after data was written on a stream. status will be 0 in case of success, < 0 otherwise. NINDENT NDENT 0.0
void (*uv_connect_cb)(uv_connect_t* req, int status) Callback called after a connection started by uv_connect() is done. status will be 0 in case of success, < 0 otherwise. NINDENT NDENT 0.0
void (*uv_shutdown_cb)(uv_shutdown_t* req, int status) Callback called after a shutdown request has been completed. status will be 0 in case of success, < 0 otherwise. NINDENT NDENT 0.0
void (*uv_connection_cb)(uv_stream_t* server, int status) Callback called when a stream server has received an incoming connection. The user can accept the connection by calling \%uv_accept(). status will be 0 in case of success, < 0 otherwise. NINDENT
size_t uv_stream_t.write_queue_size Contains the amount of queued bytes waiting to be sent. Readonly. NINDENT NDENT 0.0
uv_stream_t* uv_connect_t.handle Pointer to the stream where this connection request is running. NINDENT NDENT 0.0
uv_stream_t* uv_shutdown_t.handle Pointer to the stream where this shutdown request is running. NINDENT NDENT 0.0
uv_stream_t* uv_write_t.handle Pointer to the stream where this write request is running. NINDENT NDENT 0.0
uv_stream_t* uv_write_t.send_handle Pointer to the stream being sent using this write request. NINDENT SEE ALSO: NDENT 0.0 NDENT 3.5 The uv_handle_t members also apply. NINDENT NINDENT
int uv_shutdown(uv_shutdown_t* req, uv_stream_t* handle, uv_shutdown_cb cb) Shutdown the outgoing (write) side of a duplex stream. It waits for pending write requests to complete. The handle should refer to a initialized stream. req should be an uninitialized shutdown request struct. The cb is called after shutdown is complete. NINDENT NDENT 0.0
int uv_listen(uv_stream_t* stream, int backlog, uv_connection_cb cb) Start listening for incoming connections. backlog indicates the number of connections the kernel might queue, same as \%listen(2). When a new incoming connection is received the \%uv_connection_cb callback is called. NINDENT NDENT 0.0
int uv_accept(uv_stream_t* server, uv_stream_t* client) This call is used in conjunction with \%uv_listen() to accept incoming connections. Call this function after receiving a \%uv_connection_cb to accept the connection. Before calling this function the client handle must be initialized. < 0 return value indicates an error. When the \%uv_connection_cb callback is called it is guaranteed that this function will complete successfully the first time. If you attempt to use it more than once, it may fail. It is suggested to only call this function once per \%uv_connection_cb call. NOTE: NDENT 7.0 NDENT 3.5 server and client must be handles running on the same loop. NINDENT NINDENT NINDENT NDENT 0.0
int uv_read_start(uv_stream_t* stream, uv_alloc_cb alloc_cb, uv_read_cb read_cb) Read data from an incoming stream. The \%uv_read_cb callback will be made several times until there is no more data to read or \%uv_read_stop() is called. NINDENT NDENT 0.0
int uv_read_stop(uv_stream_t*) Stop reading data from the stream. The \%uv_read_cb callback will no longer be called. This function is idempotent and may be safely called on a stopped stream. NINDENT NDENT 0.0
int uv_write(uv_write_t* req, uv_stream_t* handle, const uv_buf_t bufs[], unsigned int nbufs, uv_write_cb cb) Write data to stream. Buffers are written in order. Example: NDENT 7.0 NDENT 3.5
void cb(uv_write_t* req, int status) { /* Logic which handles the write result */ } uv_buf_t a[] = { { .base = "1", .len = 1 }, { .base = "2", .len = 1 } }; uv_buf_t b[] = { { .base = "3", .len = 1 }, { .base = "4", .len = 1 } }; uv_write_t req1; uv_write_t req2; /* writes "1234" */ uv_write(&req1, stream, a, 2, cb); uv_write(&req2, stream, b, 2, cb);NINDENT NINDENT NOTE: NDENT 7.0 NDENT 3.5 The memory pointed to by the buffers must remain valid until the callback gets called. This also holds for \%uv_write2(). NINDENT NINDENT NINDENT NDENT 0.0
int uv_write2(uv_write_t* req, uv_stream_t* handle, const uv_buf_t bufs[], unsigned int nbufs, uv_stream_t* send_handle, uv_write_cb cb) Extended write function for sending handles over a pipe. The pipe must be initialized with ipc == 1. NOTE: NDENT 7.0 NDENT 3.5 send_handle must be a TCP socket or pipe, which is a server or a connection (listening or connected state). Bound sockets or pipes will be assumed to be servers. NINDENT NINDENT NINDENT NDENT 0.0
int uv_try_write(uv_stream_t* handle, const uv_buf_t bufs[], unsigned int nbufs) Same as \%uv_write(), but won\(aqt queue a write request if it can\(aqt be completed immediately. Will return either: NDENT 7.0
int uv_is_readable(const uv_stream_t* handle) Returns 1 if the stream is readable, 0 otherwise. NINDENT NDENT 0.0
int uv_is_writable(const uv_stream_t* handle) Returns 1 if the stream is writable, 0 otherwise. NINDENT NDENT 0.0
int uv_stream_set_blocking(uv_stream_t* handle, int blocking) Enable or disable blocking mode for a stream. When blocking mode is enabled all writes complete synchronously. The interface remains unchanged otherwise, e.g. completion or failure of the operation will still be reported through a callback which is made asynchronously. WARNING: NDENT 7.0 NDENT 3.5 Relying too much on this API is not recommended. It is likely to change significantly in the future. Currently only works on Windows for uv_pipe_t handles. On UNIX platforms, all \%uv_stream_t handles are supported. Also libuv currently makes no ordering guarantee when the blocking mode is changed after write requests have already been submitted. Therefore it is recommended to set the blocking mode immediately after opening or creating the stream. NINDENT NINDENT Changed in version 1.4.0: UNIX implementation added. NINDENT NDENT 0.0
size_t uv_stream_get_write_queue_size(const uv_stream_t* stream) Returns stream->write_queue_size. New in version 1.19.0. NINDENT SEE ALSO: NDENT 0.0 NDENT 3.5 The uv_handle_t API functions also apply. NINDENT NINDENT
uv_tcp_t TCP handle type. NINDENT
int uv_tcp_init(uv_loop_t* loop, uv_tcp_t* handle) Initialize the handle. No socket is created as of yet. NINDENT NDENT 0.0
int uv_tcp_init_ex(uv_loop_t* loop, uv_tcp_t* handle, unsigned int flags) Initialize the handle with the specified flags. At the moment only the lower 8 bits of the flags parameter are used as the socket domain. A socket will be created for the given domain. If the specified domain is AF_UNSPEC no socket is created, just like \%uv_tcp_init(). New in version 1.7.0. NINDENT NDENT 0.0
int uv_tcp_open(uv_tcp_t* handle, uv_os_sock_t sock) Open an existing file descriptor or SOCKET as a TCP handle. Changed in version 1.2.1: the file descriptor is set to non-blocking mode. NOTE: NDENT 7.0 NDENT 3.5 The passed file descriptor or SOCKET is not checked for its type, but it\(aqs required that it represents a valid stream socket. NINDENT NINDENT NINDENT NDENT 0.0
int uv_tcp_nodelay(uv_tcp_t* handle, int enable) Enable TCP_NODELAY, which disables Nagle\(aqs algorithm. NINDENT NDENT 0.0
int uv_tcp_keepalive(uv_tcp_t* handle, int enable, unsigned int delay) Enable / disable TCP keep-alive. delay is the initial delay in seconds, ignored when enable is zero. After delay has been reached, 10 successive probes, each spaced 1 second from the previous one, will still happen. If the connection is still lost at the end of this procedure, then the handle is destroyed with a UV_ETIMEDOUT error passed to the corresponding callback. NINDENT NDENT 0.0
int uv_tcp_simultaneous_accepts(uv_tcp_t* handle, int enable) Enable / disable simultaneous asynchronous accept requests that are queued by the operating system when listening for new TCP connections. This setting is used to tune a TCP server for the desired performance. Having simultaneous accepts can significantly improve the rate of accepting connections (which is why it is enabled by default) but may lead to uneven load distribution in multi-process setups. NINDENT NDENT 0.0
int uv_tcp_bind(uv_tcp_t* handle, const struct sockaddr* addr, unsigned int flags) Bind the handle to an address and port. addr should point to an initialized struct sockaddr_in or struct sockaddr_in6. When the port is already taken, you can expect to see an UV_EADDRINUSE error from either \%uv_tcp_bind(), uv_listen() or \%uv_tcp_connect(). That is, a successful call to this function does not guarantee that the call to uv_listen() or \%uv_tcp_connect() will succeed as well. flags can contain UV_TCP_IPV6ONLY, in which case dual-stack support is disabled and only IPv6 is used. NINDENT NDENT 0.0
int uv_tcp_getsockname(const uv_tcp_t* handle, struct sockaddr* name, int* namelen) Get the current address to which the handle is bound. name must point to a valid and big enough chunk of memory, struct sockaddr_storage is recommended for IPv4 and IPv6 support. NINDENT NDENT 0.0
int uv_tcp_getpeername(const uv_tcp_t* handle, struct sockaddr* name, int* namelen) Get the address of the peer connected to the handle. name must point to a valid and big enough chunk of memory, struct sockaddr_storage is recommended for IPv4 and IPv6 support. NINDENT NDENT 0.0
int uv_tcp_connect(uv_connect_t* req, uv_tcp_t* handle, const struct sockaddr* addr, uv_connect_cb cb) Establish an IPv4 or IPv6 TCP connection. Provide an initialized TCP handle and an uninitialized uv_connect_t. addr should point to an initialized struct sockaddr_in or struct sockaddr_in6. On Windows if the addr is initialized to point to an unspecified address (0.0.0.0 or ::) it will be changed to point to localhost. This is done to match the behavior of Linux systems. The callback is made when the connection has been established or when a connection error happened. Changed in version 1.19.0: added 0.0.0.0 and :: to localhost mapping NINDENT SEE ALSO: NDENT 0.0 NDENT 3.5 The uv_stream_t API functions also apply. NINDENT NINDENT NDENT 0.0
int uv_tcp_close_reset(uv_tcp_t* handle, uv_close_cb close_cb) Resets a TCP connection by sending a RST packet. This is accomplished by setting the SO_LINGER socket option with a linger interval of zero and then calling uv_close(). Due to some platform inconsistencies, mixing of uv_shutdown() and \%uv_tcp_close_reset() calls is not allowed. New in version 1.32.0. NINDENT
uv_pipe_t Pipe handle type. NINDENT
int uv_pipe_t.ipc Whether this pipe is suitable for handle passing between processes. Only a connected pipe that will be passing the handles should have this flag set, not the listening pipe that uv_accept is called on. NINDENT SEE ALSO: NDENT 0.0 NDENT 3.5 The uv_stream_t members also apply. NINDENT NINDENT
int uv_pipe_init(uv_loop_t* loop, uv_pipe_t* handle, int ipc) Initialize a pipe handle. The ipc argument is a boolean to indicate if this pipe will be used for handle passing between processes (which may change the bytes on the wire). Only a connected pipe that will be passing the handles should have this flag set, not the listening pipe that uv_accept is called on. NINDENT NDENT 0.0
int uv_pipe_open(uv_pipe_t* handle, uv_file file) Open an existing file descriptor or HANDLE as a pipe. Changed in version 1.2.1: the file descriptor is set to non-blocking mode. NOTE: NDENT 7.0 NDENT 3.5 The passed file descriptor or HANDLE is not checked for its type, but it\(aqs required that it represents a valid pipe. NINDENT NINDENT NINDENT NDENT 0.0
int uv_pipe_bind(uv_pipe_t* handle, const char* name) Bind the pipe to a file path (Unix) or a name (Windows). NOTE: NDENT 7.0 NDENT 3.5 Paths on Unix get truncated to sizeof(sockaddr_un.sun_path) bytes, typically between 92 and 108 bytes. NINDENT NINDENT NINDENT NDENT 0.0
void uv_pipe_connect(uv_connect_t* req, uv_pipe_t* handle, const char* name, uv_connect_cb cb) Connect to the Unix domain socket or the named pipe. NOTE: NDENT 7.0 NDENT 3.5 Paths on Unix get truncated to sizeof(sockaddr_un.sun_path) bytes, typically between 92 and 108 bytes. NINDENT NINDENT NINDENT NDENT 0.0
int uv_pipe_getsockname(const uv_pipe_t* handle, char* buffer, size_t* size) Get the name of the Unix domain socket or the named pipe. A preallocated buffer must be provided. The size parameter holds the length of the buffer and it\(aqs set to the number of bytes written to the buffer on output. If the buffer is not big enough UV_ENOBUFS will be returned and len will contain the required size. Changed in version 1.3.0: the returned length no longer includes the terminating null byte, and the buffer is not null terminated. NINDENT NDENT 0.0
int uv_pipe_getpeername(const uv_pipe_t* handle, char* buffer, size_t* size) Get the name of the Unix domain socket or the named pipe to which the handle is connected. A preallocated buffer must be provided. The size parameter holds the length of the buffer and it\(aqs set to the number of bytes written to the buffer on output. If the buffer is not big enough UV_ENOBUFS will be returned and len will contain the required size. New in version 1.3.0. NINDENT NDENT 0.0
void uv_pipe_pending_instances(uv_pipe_t* handle, int count) Set the number of pending pipe instance handles when the pipe server is waiting for connections. NOTE: NDENT 7.0 NDENT 3.5 This setting applies to Windows only. NINDENT NINDENT NINDENT NDENT 0.0
int uv_pipe_pending_count(uv_pipe_t* handle) NINDENT NDENT 0.0
uv_handle_type uv_pipe_pending_type(uv_pipe_t* handle) Used to receive handles over IPC pipes. First - call \%uv_pipe_pending_count(), if it\(aqs > 0 then initialize a handle of the given type, returned by \%uv_pipe_pending_type() and call uv_accept(pipe, handle). NINDENT SEE ALSO: NDENT 0.0 NDENT 3.5 The uv_stream_t API functions also apply. NINDENT NINDENT NDENT 0.0
int uv_pipe_chmod(uv_pipe_t* handle, int flags) Alters pipe permissions, allowing it to be accessed from processes run by different users. Makes the pipe writable or readable by all users. Mode can be UV_WRITABLE, UV_READABLE or UV_WRITABLE | UV_READABLE. This function is blocking. New in version 1.16.0. NINDENT
uv_tty_t TTY handle type. NINDENT NDENT 0.0
uv_tty_mode_t New in version 1.2.0. TTY mode type: NDENT 7.0 NDENT 3.5
typedef enum { /* Initial/normal terminal mode */ UV_TTY_MODE_NORMAL, /* Raw input mode (On Windows, ENABLE_WINDOW_INPUT is also enabled) */ UV_TTY_MODE_RAW, /* Binary-safe I/O mode for IPC (Unix-only) */ UV_TTY_MODE_IO } uv_tty_mode_t;NINDENT NINDENT NINDENT NDENT 0.0
uv_tty_vtermstate_t
Console virtual terminal mode type: NDENT 7.0 NDENT 3.5
typedef enum { /* * The console supports handling of virtual terminal sequences * (Windows10 new console, ConEmu) */ UV_TTY_SUPPORTED, /* The console cannot process virtual terminal sequences. (Legacy * console) */ UV_TTY_UNSUPPORTED } uv_tty_vtermstate_tNINDENT NINDENT NINDENT
int uv_tty_init(uv_loop_t* loop, uv_tty_t* handle, uv_file fd, int unused) Initialize a new TTY stream with the given file descriptor. Usually the file descriptor will be: NDENT 7.0
int uv_tty_set_mode(uv_tty_t* handle, uv_tty_mode_t mode) Changed in version 1.2.0:: the mode is specified as a \%uv_tty_mode_t value. Set the TTY using the specified terminal mode. NINDENT NDENT 0.0
int uv_tty_reset_mode(void) To be called when the program exits. Resets TTY settings to default values for the next process to take over. This function is async signal-safe on Unix platforms but can fail with error code UV_EBUSY if you call it when execution is inside \%uv_tty_set_mode(). NINDENT NDENT 0.0
int uv_tty_get_winsize(uv_tty_t* handle, int* width, int* height) Gets the current Window size. On success it returns 0. NINDENT SEE ALSO: NDENT 0.0 NDENT 3.5 The uv_stream_t API functions also apply. NINDENT NINDENT NDENT 0.0
void uv_tty_set_vterm_state(uv_tty_vtermstate_t state) Controls whether console virtual terminal sequences are processed by libuv or console. Useful in particular for enabling ConEmu support of ANSI X3.64 and Xterm 256 colors. Otherwise Windows10 consoles are usually detected automatically. This function is only meaningful on Windows systems. On Unix it is silently ignored. New in version 1.33.0. NINDENT NDENT 0.0
int uv_tty_get_vterm_state(uv_tty_vtermstate_t* state) Get the current state of whether console virtual terminal sequences are handled by libuv or the console. This function is not implemented on Unix, where it returns UV_ENOTSUP. New in version 1.33.0. NINDENT
uv_udp_t UDP handle type. NINDENT NDENT 0.0
uv_udp_send_t UDP send request type. NINDENT NDENT 0.0
uv_udp_flags Flags used in \%uv_udp_bind() and \%uv_udp_recv_cb.. NDENT 7.0 NDENT 3.5
enum uv_udp_flags { /* Disables dual stack mode. */ UV_UDP_IPV6ONLY = 1, /* * Indicates message was truncated because read buffer was too small. The * remainder was discarded by the OS. Used in uv_udp_recv_cb. */ UV_UDP_PARTIAL = 2, /* * Indicates if SO_REUSEADDR will be set when binding the handle in * uv_udp_bind. * This sets the SO_REUSEPORT socket flag on the BSDs and OS X. On other * Unix platforms, it sets the SO_REUSEADDR flag. What that means is that * multiple threads or processes can bind to the same address without error * (provided they all set the flag) but only the last one to bind will receive * any traffic, in effect "stealing" the port from the previous listener. */ UV_UDP_REUSEADDR = 4, /* * Indicates that the message was received by recvmmsg, so the buffer provided * must not be freed by the recv_cb callback. */ UV_UDP_MMSG_CHUNK = 8, /* * Indicates that recvmmsg should be used, if available. */ UV_UDP_RECVMMSG = 256 };NINDENT NINDENT NINDENT NDENT 0.0
void (*uv_udp_send_cb)(uv_udp_send_t* req, int status) Type definition for callback passed to \%uv_udp_send(), which is called after the data was sent. NINDENT NDENT 0.0
void (*uv_udp_recv_cb)(uv_udp_t* handle, ssize_t nread, const uv_buf_t* buf, const struct sockaddr* addr, unsigned flags) Type definition for callback passed to \%uv_udp_recv_start(), which is called when the endpoint receives data. NDENT 7.0
uv_membership Membership type for a multicast address. NDENT 7.0 NDENT 3.5
typedef enum { UV_LEAVE_GROUP = 0, UV_JOIN_GROUP } uv_membership;NINDENT NINDENT NINDENT
size_t uv_udp_t.send_queue_size Number of bytes queued for sending. This field strictly shows how much information is currently queued. NINDENT NDENT 0.0
size_t uv_udp_t.send_queue_count Number of send requests currently in the queue awaiting to be processed. NINDENT NDENT 0.0
uv_udp_t* uv_udp_send_t.handle UDP handle where this send request is taking place. NINDENT SEE ALSO: NDENT 0.0 NDENT 3.5 The uv_handle_t members also apply. NINDENT NINDENT
int uv_udp_init(uv_loop_t* loop, uv_udp_t* handle) Initialize a new UDP handle. The actual socket is created lazily. Returns 0 on success. NINDENT NDENT 0.0
int uv_udp_init_ex(uv_loop_t* loop, uv_udp_t* handle, unsigned int flags) Initialize the handle with the specified flags. The lower 8 bits of the flags parameter are used as the socket domain. A socket will be created for the given domain. If the specified domain is AF_UNSPEC no socket is created, just like \%uv_udp_init(). The remaining bits can be used to set one of these flags: NDENT 7.0
int uv_udp_open(uv_udp_t* handle, uv_os_sock_t sock) Opens an existing file descriptor or Windows SOCKET as a UDP handle. Unix only: The only requirement of the sock argument is that it follows the datagram contract (works in unconnected mode, supports sendmsg()/recvmsg(), etc). In other words, other datagram-type sockets like raw sockets or netlink sockets can also be passed to this function. Changed in version 1.2.1: the file descriptor is set to non-blocking mode. NOTE: NDENT 7.0 NDENT 3.5 The passed file descriptor or SOCKET is not checked for its type, but it\(aqs required that it represents a valid datagram socket. NINDENT NINDENT NINDENT NDENT 0.0
int uv_udp_bind(uv_udp_t* handle, const struct sockaddr* addr, unsigned int flags) Bind the UDP handle to an IP address and port. NDENT 7.0
Parameters NDENT 7.0
Returns 0 on success, or an error code < 0 on failure. NINDENT NINDENT NDENT 0.0
int uv_udp_connect(uv_udp_t* handle, const struct sockaddr* addr) Associate the UDP handle to a remote address and port, so every message sent by this handle is automatically sent to that destination. Calling this function with a NULL addr disconnects the handle. Trying to call uv_udp_connect() on an already connected handle will result in an UV_EISCONN error. Trying to disconnect a handle that is not connected will return an UV_ENOTCONN error. NDENT 7.0
Parameters NDENT 7.0
Returns 0 on success, or an error code < 0 on failure. NINDENT New in version 1.27.0. NINDENT NDENT 0.0
int uv_udp_getpeername(const uv_udp_t* handle, struct sockaddr* name, int* namelen) Get the remote IP and port of the UDP handle on connected UDP handles. On unconnected handles, it returns UV_ENOTCONN. NDENT 7.0
Parameters NDENT 7.0
Returns 0 on success, or an error code < 0 on failure NINDENT New in version 1.27.0. NINDENT NDENT 0.0
int uv_udp_getsockname(const uv_udp_t* handle, struct sockaddr* name, int* namelen) Get the local IP and port of the UDP handle. NDENT 7.0
Parameters NDENT 7.0
Returns 0 on success, or an error code < 0 on failure. NINDENT NINDENT NDENT 0.0
int uv_udp_set_membership(uv_udp_t* handle, const char* multicast_addr, const char* interface_addr, uv_membership membership) Set membership for a multicast address NDENT 7.0
Parameters NDENT 7.0
Returns 0 on success, or an error code < 0 on failure. NINDENT NINDENT NDENT 0.0
int uv_udp_set_source_membership(uv_udp_t* handle, const char* multicast_addr, const char* interface_addr, const char* source_addr, uv_membership membership) Set membership for a source-specific multicast group. NDENT 7.0
Parameters NDENT 7.0
Returns 0 on success, or an error code < 0 on failure. NINDENT New in version 1.32.0. NINDENT NDENT 0.0
int uv_udp_set_multicast_loop(uv_udp_t* handle, int on) Set IP multicast loop flag. Makes multicast packets loop back to local sockets. NDENT 7.0
Parameters NDENT 7.0
Returns 0 on success, or an error code < 0 on failure. NINDENT NINDENT NDENT 0.0
int uv_udp_set_multicast_ttl(uv_udp_t* handle, int ttl) Set the multicast ttl. NDENT 7.0
Parameters NDENT 7.0
Returns 0 on success, or an error code < 0 on failure. NINDENT NINDENT NDENT 0.0
int uv_udp_set_multicast_interface(uv_udp_t* handle, const char* interface_addr) Set the multicast interface to send or receive data on. NDENT 7.0
Parameters NDENT 7.0
Returns 0 on success, or an error code < 0 on failure. NINDENT NINDENT NDENT 0.0
int uv_udp_set_broadcast(uv_udp_t* handle, int on) Set broadcast on or off. NDENT 7.0
Parameters NDENT 7.0
Returns 0 on success, or an error code < 0 on failure. NINDENT NINDENT NDENT 0.0
int uv_udp_set_ttl(uv_udp_t* handle, int ttl) Set the time to live. NDENT 7.0
Parameters NDENT 7.0
Returns 0 on success, or an error code < 0 on failure. NINDENT NINDENT NDENT 0.0
int uv_udp_send(uv_udp_send_t* req, uv_udp_t* handle, const uv_buf_t bufs[], unsigned int nbufs, const struct sockaddr* addr, uv_udp_send_cb send_cb) Send data over the UDP socket. If the socket has not previously been bound with \%uv_udp_bind() it will be bound to 0.0.0.0 (the "all interfaces" IPv4 address) and a random port number. On Windows if the addr is initialized to point to an unspecified address (0.0.0.0 or ::) it will be changed to point to localhost. This is done to match the behavior of Linux systems. For connected UDP handles, addr must be set to NULL, otherwise it will return UV_EISCONN error. For connectionless UDP handles, addr cannot be NULL, otherwise it will return UV_EDESTADDRREQ error. NDENT 7.0
Parameters NDENT 7.0
Returns 0 on success, or an error code < 0 on failure. NINDENT Changed in version 1.19.0: added 0.0.0.0 and :: to localhost mapping Changed in version 1.27.0: added support for connected sockets NINDENT NDENT 0.0
int uv_udp_try_send(uv_udp_t* handle, const uv_buf_t bufs[], unsigned int nbufs, const struct sockaddr* addr) Same as \%uv_udp_send(), but won\(aqt queue a send request if it can\(aqt be completed immediately. For connected UDP handles, addr must be set to NULL, otherwise it will return UV_EISCONN error. For connectionless UDP handles, addr cannot be NULL, otherwise it will return UV_EDESTADDRREQ error. NDENT 7.0
Returns >= 0: number of bytes sent (it matches the given buffer size). < 0: negative error code (UV_EAGAIN is returned when the message can\(aqt be sent immediately). NINDENT Changed in version 1.27.0: added support for connected sockets NINDENT NDENT 0.0
int uv_udp_recv_start(uv_udp_t* handle, uv_alloc_cb alloc_cb, uv_udp_recv_cb recv_cb) Prepare for receiving data. If the socket has not previously been bound with \%uv_udp_bind() it is bound to 0.0.0.0 (the "all interfaces" IPv4 address) and a random port number. NDENT 7.0
Parameters NDENT 7.0
Returns 0 on success, or an error code < 0 on failure. NINDENT Changed in version 1.35.0: added support for \%recvmmsg(2) on supported platforms). The use of this feature requires a buffer larger than 2 * 64KB to be passed to alloc_cb. Changed in version 1.37.0: \%recvmmsg(2) support is no longer enabled implicitly, it must be explicitly requested by passing the UV_UDP_RECVMMSG flag to \%uv_udp_init_ex(). NINDENT NDENT 0.0
int uv_udp_recv_stop(uv_udp_t* handle) Stop listening for incoming datagrams. NDENT 7.0
Parameters NDENT 7.0
Returns 0 on success, or an error code < 0 on failure. NINDENT NINDENT NDENT 0.0
size_t uv_udp_get_send_queue_size(const uv_udp_t* handle) Returns handle->send_queue_size. New in version 1.19.0. NINDENT NDENT 0.0
size_t uv_udp_get_send_queue_count(const uv_udp_t* handle) Returns handle->send_queue_count. New in version 1.19.0. NINDENT SEE ALSO: NDENT 0.0 NDENT 3.5 The uv_handle_t API functions also apply. NINDENT NINDENT
uv_fs_event_t FS Event handle type. NINDENT NDENT 0.0
void (*uv_fs_event_cb)(uv_fs_event_t* handle, const char* filename, int events, int status) Callback passed to \%uv_fs_event_start() which will be called repeatedly after the handle is started. If the handle was started with a directory the filename parameter will be a relative path to a file contained in the directory. The events parameter is an ORed mask of \%uv_fs_event elements. NINDENT NDENT 0.0
uv_fs_event Event types that \%uv_fs_event_t handles monitor. NDENT 7.0 NDENT 3.5
enum uv_fs_event { UV_RENAME = 1, UV_CHANGE = 2 };NINDENT NINDENT NINDENT NDENT 0.0
uv_fs_event_flags Flags that can be passed to \%uv_fs_event_start() to control its behavior. NDENT 7.0 NDENT 3.5
enum uv_fs_event_flags { /* * By default, if the fs event watcher is given a directory name, we will * watch for all events in that directory. This flags overrides this behavior * and makes fs_event report only changes to the directory entry itself. This * flag does not affect individual files watched. * This flag is currently not implemented yet on any backend. */ UV_FS_EVENT_WATCH_ENTRY = 1, /* * By default uv_fs_event will try to use a kernel interface such as inotify * or kqueue to detect events. This may not work on remote file systems such * as NFS mounts. This flag makes fs_event fall back to calling stat() on a * regular interval. * This flag is currently not implemented yet on any backend. */ UV_FS_EVENT_STAT = 2, /* * By default, event watcher, when watching directory, is not registering * (is ignoring) changes in its subdirectories. * This flag will override this behaviour on platforms that support it. */ UV_FS_EVENT_RECURSIVE = 4 };NINDENT NINDENT NINDENT
int uv_fs_event_init(uv_loop_t* loop, uv_fs_event_t* handle) Initialize the handle. NINDENT NDENT 0.0
int uv_fs_event_start(uv_fs_event_t* handle, uv_fs_event_cb cb, const char* path, unsigned int flags) Start the handle with the given callback, which will watch the specified path for changes. flags can be an ORed mask of \%uv_fs_event_flags. NOTE: NDENT 7.0 NDENT 3.5 Currently the only supported flag is UV_FS_EVENT_RECURSIVE and only on OSX and Windows. NINDENT NINDENT NINDENT NDENT 0.0
int uv_fs_event_stop(uv_fs_event_t* handle) Stop the handle, the callback will no longer be called. NINDENT NDENT 0.0
int uv_fs_event_getpath(uv_fs_event_t* handle, char* buffer, size_t* size) Get the path being monitored by the handle. The buffer must be preallocated by the user. Returns 0 on success or an error code < 0 in case of failure. On success, buffer will contain the path and size its length. If the buffer is not big enough UV_ENOBUFS will be returned and size will be set to the required size, including the null terminator. Changed in version 1.3.0: the returned length no longer includes the terminating null byte, and the buffer is not null terminated. Changed in version 1.9.0: the returned length includes the terminating null byte on UV_ENOBUFS, and the buffer is null terminated on success. NINDENT SEE ALSO: NDENT 0.0 NDENT 3.5 The uv_handle_t API functions also apply. NINDENT NINDENT
uv_fs_poll_t FS Poll handle type. NINDENT NDENT 0.0
void (*uv_fs_poll_cb)(uv_fs_poll_t* handle, int status, const uv_stat_t* prev, const uv_stat_t* curr) Callback passed to \%uv_fs_poll_start() which will be called repeatedly after the handle is started, when any change happens to the monitored path. The callback is invoked with status < 0 if path does not exist or is inaccessible. The watcher is not stopped but your callback is not called again until something changes (e.g. when the file is created or the error reason changes). When status == 0, the callback receives pointers to the old and new uv_stat_t structs. They are valid for the duration of the callback only. NINDENT
int uv_fs_poll_init(uv_loop_t* loop, uv_fs_poll_t* handle) Initialize the handle. NINDENT NDENT 0.0
int uv_fs_poll_start(uv_fs_poll_t* handle, uv_fs_poll_cb poll_cb, const char* path, unsigned int interval) Check the file at path for changes every interval milliseconds. NOTE: NDENT 7.0 NDENT 3.5 For maximum portability, use multi-second intervals. Sub-second intervals will not detect all changes on many file systems. NINDENT NINDENT NINDENT NDENT 0.0
int uv_fs_poll_stop(uv_fs_poll_t* handle) Stop the handle, the callback will no longer be called. NINDENT NDENT 0.0
int uv_fs_poll_getpath(uv_fs_poll_t* handle, char* buffer, size_t* size) Get the path being monitored by the handle. The buffer must be preallocated by the user. Returns 0 on success or an error code < 0 in case of failure. On success, buffer will contain the path and size its length. If the buffer is not big enough UV_ENOBUFS will be returned and size will be set to the required size. Changed in version 1.3.0: the returned length no longer includes the terminating null byte, and the buffer is not null terminated. Changed in version 1.9.0: the returned length includes the terminating null byte on UV_ENOBUFS, and the buffer is null terminated on success. NINDENT SEE ALSO: NDENT 0.0 NDENT 3.5 The uv_handle_t API functions also apply. NINDENT NINDENT
uv_fs_t File system request type. NINDENT NDENT 0.0
uv_timespec_t Portable equivalent of struct timespec. NDENT 7.0 NDENT 3.5
typedef struct { long tv_sec; long tv_nsec; } uv_timespec_t;NINDENT NINDENT NINDENT NDENT 0.0
uv_stat_t Portable equivalent of struct stat. NDENT 7.0 NDENT 3.5
typedef struct { uint64_t st_dev; uint64_t st_mode; uint64_t st_nlink; uint64_t st_uid; uint64_t st_gid; uint64_t st_rdev; uint64_t st_ino; uint64_t st_size; uint64_t st_blksize; uint64_t st_blocks; uint64_t st_flags; uint64_t st_gen; uv_timespec_t st_atim; uv_timespec_t st_mtim; uv_timespec_t st_ctim; uv_timespec_t st_birthtim; } uv_stat_t;NINDENT NINDENT NINDENT NDENT 0.0
uv_fs_type File system request type. NDENT 7.0 NDENT 3.5
typedef enum { UV_FS_UNKNOWN = -1, UV_FS_CUSTOM, UV_FS_OPEN, UV_FS_CLOSE, UV_FS_READ, UV_FS_WRITE, UV_FS_SENDFILE, UV_FS_STAT, UV_FS_LSTAT, UV_FS_FSTAT, UV_FS_FTRUNCATE, UV_FS_UTIME, UV_FS_FUTIME, UV_FS_ACCESS, UV_FS_CHMOD, UV_FS_FCHMOD, UV_FS_FSYNC, UV_FS_FDATASYNC, UV_FS_UNLINK, UV_FS_RMDIR, UV_FS_MKDIR, UV_FS_MKDTEMP, UV_FS_RENAME, UV_FS_SCANDIR, UV_FS_LINK, UV_FS_SYMLINK, UV_FS_READLINK, UV_FS_CHOWN, UV_FS_FCHOWN, UV_FS_REALPATH, UV_FS_COPYFILE, UV_FS_LCHOWN, UV_FS_OPENDIR, UV_FS_READDIR, UV_FS_CLOSEDIR, UV_FS_MKSTEMP, UV_FS_LUTIME } uv_fs_type;NINDENT NINDENT NINDENT NDENT 0.0
uv_statfs_t Reduced cross platform equivalent of struct statfs. Used in \%uv_fs_statfs(). NDENT 7.0 NDENT 3.5
typedef struct uv_statfs_s { uint64_t f_type; uint64_t f_bsize; uint64_t f_blocks; uint64_t f_bfree; uint64_t f_bavail; uint64_t f_files; uint64_t f_ffree; uint64_t f_spare[4]; } uv_statfs_t;NINDENT NINDENT NINDENT NDENT 0.0
uv_dirent_t Cross platform (reduced) equivalent of struct dirent. Used in \%uv_fs_scandir_next(). NDENT 7.0 NDENT 3.5
typedef enum { UV_DIRENT_UNKNOWN, UV_DIRENT_FILE, UV_DIRENT_DIR, UV_DIRENT_LINK, UV_DIRENT_FIFO, UV_DIRENT_SOCKET, UV_DIRENT_CHAR, UV_DIRENT_BLOCK } uv_dirent_type_t; typedef struct uv_dirent_s { const char* name; uv_dirent_type_t type; } uv_dirent_t;NINDENT NINDENT NINDENT NDENT 0.0
uv_dir_t Data type used for streaming directory iteration. Used by \%uv_fs_opendir(), \%uv_fs_readdir(), and \%uv_fs_closedir(). dirents represents a user provided array of uv_dirent_t\(gas used to hold results. \(ganentries is the user provided maximum array size of dirents. NDENT 7.0 NDENT 3.5
typedef struct uv_dir_s { uv_dirent_t* dirents; size_t nentries; } uv_dir_t;NINDENT NINDENT NINDENT
uv_loop_t* uv_fs_t.loop Loop that started this request and where completion will be reported. Readonly. NINDENT NDENT 0.0
uv_fs_type uv_fs_t.fs_type FS request type. NINDENT NDENT 0.0
const char* uv_fs_t.path Path affecting the request. NINDENT NDENT 0.0
ssize_t uv_fs_t.result Result of the request. < 0 means error, success otherwise. On requests such as \%uv_fs_read() or \%uv_fs_write() it indicates the amount of data that was read or written, respectively. NINDENT NDENT 0.0
uv_stat_t uv_fs_t.statbuf Stores the result of \%uv_fs_stat() and other stat requests. NINDENT NDENT 0.0
void* uv_fs_t.ptr Stores the result of \%uv_fs_readlink() and \%uv_fs_realpath() and serves as an alias to statbuf. NINDENT SEE ALSO: NDENT 0.0 NDENT 3.5 The uv_req_t members also apply. NINDENT NINDENT
void uv_fs_req_cleanup(uv_fs_t* req) Cleanup request. Must be called after a request is finished to deallocate any memory libuv might have allocated. NINDENT NDENT 0.0
int uv_fs_close(uv_loop_t* loop, uv_fs_t* req, uv_file file, uv_fs_cb cb) Equivalent to \%close(2). NINDENT NDENT 0.0
int uv_fs_open(uv_loop_t* loop, uv_fs_t* req, const char* path, int flags, int mode, uv_fs_cb cb) Equivalent to \%open(2). NOTE: NDENT 7.0 NDENT 3.5 On Windows libuv uses CreateFileW and thus the file is always opened in binary mode. Because of this the O_BINARY and O_TEXT flags are not supported. NINDENT NINDENT NINDENT NDENT 0.0
int uv_fs_read(uv_loop_t* loop, uv_fs_t* req, uv_file file, const uv_buf_t bufs[], unsigned int nbufs, int64_t offset, uv_fs_cb cb) Equivalent to \%preadv(2). WARNING: NDENT 7.0 NDENT 3.5 On Windows, under non-MSVC environments (e.g. when GCC or Clang is used to build libuv), files opened using UV_FS_O_FILEMAP may cause a fatal crash if the memory mapped read operation fails. NINDENT NINDENT NINDENT NDENT 0.0
int uv_fs_unlink(uv_loop_t* loop, uv_fs_t* req, const char* path, uv_fs_cb cb) Equivalent to \%unlink(2). NINDENT NDENT 0.0
int uv_fs_write(uv_loop_t* loop, uv_fs_t* req, uv_file file, const uv_buf_t bufs[], unsigned int nbufs, int64_t offset, uv_fs_cb cb) Equivalent to \%pwritev(2). WARNING: NDENT 7.0 NDENT 3.5 On Windows, under non-MSVC environments (e.g. when GCC or Clang is used to build libuv), files opened using UV_FS_O_FILEMAP may cause a fatal crash if the memory mapped write operation fails. NINDENT NINDENT NINDENT NDENT 0.0
int uv_fs_mkdir(uv_loop_t* loop, uv_fs_t* req, const char* path, int mode, uv_fs_cb cb) Equivalent to \%mkdir(2). NOTE: NDENT 7.0 NDENT 3.5 mode is currently not implemented on Windows. NINDENT NINDENT NINDENT NDENT 0.0
int uv_fs_mkdtemp(uv_loop_t* loop, uv_fs_t* req, const char* tpl, uv_fs_cb cb) Equivalent to \%mkdtemp(3). The result can be found as a null terminated string at req->path. NINDENT NDENT 0.0
int uv_fs_mkstemp(uv_loop_t* loop, uv_fs_t* req, const char* tpl, uv_fs_cb cb) Equivalent to \%mkstemp(3). The created file path can be found as a null terminated string at req->path. The file descriptor can be found as an integer at req->result. New in version 1.34.0. NINDENT NDENT 0.0
int uv_fs_rmdir(uv_loop_t* loop, uv_fs_t* req, const char* path, uv_fs_cb cb) Equivalent to \%rmdir(2). NINDENT NDENT 0.0
int uv_fs_opendir(uv_loop_t* loop, uv_fs_t* req, const char* path, uv_fs_cb cb) Opens path as a directory stream. On success, a uv_dir_t is allocated and returned via req->ptr. This memory is not freed by uv_fs_req_cleanup(), although req->ptr is set to NULL. The allocated memory must be freed by calling uv_fs_closedir(). On failure, no memory is allocated. The contents of the directory can be iterated over by passing the resulting uv_dir_t to uv_fs_readdir(). New in version 1.28.0. NINDENT NDENT 0.0
int uv_fs_closedir(uv_loop_t* loop, uv_fs_t* req, uv_dir_t* dir, uv_fs_cb cb) Closes the directory stream represented by dir and frees the memory allocated by uv_fs_opendir(). New in version 1.28.0. NINDENT NDENT 0.0
int uv_fs_readdir(uv_loop_t* loop, uv_fs_t* req, uv_dir_t* dir, uv_fs_cb cb) Iterates over the directory stream, dir, returned by a successful uv_fs_opendir() call. Prior to invoking uv_fs_readdir(), the caller must set dir->dirents and dir->nentries, representing the array of \%uv_dirent_t elements used to hold the read directory entries and its size. On success, the result is an integer >= 0 representing the number of entries read from the stream. New in version 1.28.0. WARNING: NDENT 7.0 NDENT 3.5 uv_fs_readdir() is not thread safe. NINDENT NINDENT NOTE: NDENT 7.0 NDENT 3.5 This function does not return the "." and ".." entries. NINDENT NINDENT NOTE: NDENT 7.0 NDENT 3.5 On success this function allocates memory that must be freed using uv_fs_req_cleanup(). uv_fs_req_cleanup() must be called before closing the directory with uv_fs_closedir(). NINDENT NINDENT NINDENT NDENT 0.0
int uv_fs_scandir(uv_loop_t* loop, uv_fs_t* req, const char* path, int flags, uv_fs_cb cb) NINDENT NDENT 0.0
int uv_fs_scandir_next(uv_fs_t* req, uv_dirent_t* ent) Equivalent to \%scandir(3), with a slightly different API. Once the callback for the request is called, the user can use \%uv_fs_scandir_next() to get ent populated with the next directory entry data. When there are no more entries UV_EOF will be returned. NOTE: NDENT 7.0 NDENT 3.5 Unlike scandir(3), this function does not return the "." and ".." entries. NINDENT NINDENT NOTE: NDENT 7.0 NDENT 3.5 On Linux, getting the type of an entry is only supported by some file systems (btrfs, ext2, ext3 and ext4 at the time of this writing), check the \%getdents(2) man page. NINDENT NINDENT NINDENT NDENT 0.0
int uv_fs_stat(uv_loop_t* loop, uv_fs_t* req, const char* path, uv_fs_cb cb) NINDENT NDENT 0.0
int uv_fs_fstat(uv_loop_t* loop, uv_fs_t* req, uv_file file, uv_fs_cb cb) NINDENT NDENT 0.0
int uv_fs_lstat(uv_loop_t* loop, uv_fs_t* req, const char* path, uv_fs_cb cb) Equivalent to \%stat(2), \%fstat(2) and \%lstat(2) respectively. NINDENT NDENT 0.0
int uv_fs_statfs(uv_loop_t* loop, uv_fs_t* req, const char* path, uv_fs_cb cb) Equivalent to \%statfs(2). On success, a uv_statfs_t is allocated and returned via req->ptr. This memory is freed by uv_fs_req_cleanup(). NOTE: NDENT 7.0 NDENT 3.5 Any fields in the resulting uv_statfs_t that are not supported by the underlying operating system are set to zero. NINDENT NINDENT New in version 1.31.0. NINDENT NDENT 0.0
int uv_fs_rename(uv_loop_t* loop, uv_fs_t* req, const char* path, const char* new_path, uv_fs_cb cb) Equivalent to \%rename(2). NINDENT NDENT 0.0
int uv_fs_fsync(uv_loop_t* loop, uv_fs_t* req, uv_file file, uv_fs_cb cb) Equivalent to \%fsync(2). NOTE: NDENT 7.0 NDENT 3.5 For AIX, uv_fs_fsync returns UV_EBADF on file descriptors referencing non regular files. NINDENT NINDENT NINDENT NDENT 0.0
int uv_fs_fdatasync(uv_loop_t* loop, uv_fs_t* req, uv_file file, uv_fs_cb cb) Equivalent to \%fdatasync(2). NINDENT NDENT 0.0
int uv_fs_ftruncate(uv_loop_t* loop, uv_fs_t* req, uv_file file, int64_t offset, uv_fs_cb cb) Equivalent to \%ftruncate(2). NINDENT NDENT 0.0
int uv_fs_copyfile(uv_loop_t* loop, uv_fs_t* req, const char* path, const char* new_path, int flags, uv_fs_cb cb) Copies a file from path to new_path. Supported flags are described below. NDENT 7.0
int uv_fs_sendfile(uv_loop_t* loop, uv_fs_t* req, uv_file out_fd, uv_file in_fd, int64_t in_offset, size_t length, uv_fs_cb cb) Limited equivalent to \%sendfile(2). NINDENT NDENT 0.0
int uv_fs_access(uv_loop_t* loop, uv_fs_t* req, const char* path, int mode, uv_fs_cb cb) Equivalent to \%access(2) on Unix. Windows uses GetFileAttributesW(). NINDENT NDENT 0.0
int uv_fs_chmod(uv_loop_t* loop, uv_fs_t* req, const char* path, int mode, uv_fs_cb cb) NINDENT NDENT 0.0
int uv_fs_fchmod(uv_loop_t* loop, uv_fs_t* req, uv_file file, int mode, uv_fs_cb cb) Equivalent to \%chmod(2) and \%fchmod(2) respectively. NINDENT NDENT 0.0
int uv_fs_utime(uv_loop_t* loop, uv_fs_t* req, const char* path, double atime, double mtime, uv_fs_cb cb) NINDENT NDENT 0.0
int uv_fs_futime(uv_loop_t* loop, uv_fs_t* req, uv_file file, double atime, double mtime, uv_fs_cb cb) NINDENT NDENT 0.0
int uv_fs_lutime(uv_loop_t* loop, uv_fs_t* req, const char* path, double atime, double mtime, uv_fs_cb cb) Equivalent to \%utime(2), \%futimes(3) and \%lutimes(3) respectively. NOTE: NDENT 7.0 NDENT 3.5 z/OS: uv_fs_lutime() is not implemented for z/OS. It can still be called but will return UV_ENOSYS. NINDENT NINDENT NOTE: NDENT 7.0 NDENT 3.5 AIX: uv_fs_futime() and uv_fs_lutime() functions only work for AIX 7.1 and newer. They can still be called on older versions but will return UV_ENOSYS. NINDENT NINDENT Changed in version 1.10.0: sub-second precission is supported on Windows NINDENT NDENT 0.0
int uv_fs_link(uv_loop_t* loop, uv_fs_t* req, const char* path, const char* new_path, uv_fs_cb cb) Equivalent to \%link(2). NINDENT NDENT 0.0
int uv_fs_symlink(uv_loop_t* loop, uv_fs_t* req, const char* path, const char* new_path, int flags, uv_fs_cb cb) Equivalent to \%symlink(2). NOTE: NDENT 7.0 NDENT 3.5 On Windows the flags parameter can be specified to control how the symlink will be created: NDENT 0.0 NDENT 3.5 NDENT 0.0
int uv_fs_readlink(uv_loop_t* loop, uv_fs_t* req, const char* path, uv_fs_cb cb) Equivalent to \%readlink(2). The resulting string is stored in req->ptr. NINDENT NDENT 0.0
int uv_fs_realpath(uv_loop_t* loop, uv_fs_t* req, const char* path, uv_fs_cb cb) Equivalent to \%realpath(3) on Unix. Windows uses \%GetFinalPathNameByHandle. The resulting string is stored in req->ptr. WARNING: NDENT 7.0 NDENT 3.5 This function has certain platform-specific caveats that were discovered when used in Node. NDENT 0.0
int uv_fs_chown(uv_loop_t* loop, uv_fs_t* req, const char* path, uv_uid_t uid, uv_gid_t gid, uv_fs_cb cb) NINDENT NDENT 0.0
int uv_fs_fchown(uv_loop_t* loop, uv_fs_t* req, uv_file file, uv_uid_t uid, uv_gid_t gid, uv_fs_cb cb) NINDENT NDENT 0.0
int uv_fs_lchown(uv_loop_t* loop, uv_fs_t* req, const char* path, uv_uid_t uid, uv_gid_t gid, uv_fs_cb cb) Equivalent to \%chown(2), \%fchown(2) and \%lchown(2) respectively. NOTE: NDENT 7.0 NDENT 3.5 These functions are not implemented on Windows. NINDENT NINDENT Changed in version 1.21.0: implemented uv_fs_lchown NINDENT NDENT 0.0
uv_fs_type uv_fs_get_type(const uv_fs_t* req) Returns req->fs_type. New in version 1.19.0. NINDENT NDENT 0.0
ssize_t uv_fs_get_result(const uv_fs_t* req) Returns req->result. New in version 1.19.0. NINDENT NDENT 0.0
int uv_fs_get_system_error(const uv_fs_t* req) Returns the platform specific error code - GetLastError() value on Windows and -(req->result) on other platforms. New in version 1.38.0. NINDENT NDENT 0.0
void* uv_fs_get_ptr(const uv_fs_t* req) Returns req->ptr. New in version 1.19.0. NINDENT NDENT 0.0
const char* uv_fs_get_path(const uv_fs_t* req) Returns req->path. New in version 1.19.0. NINDENT NDENT 0.0
uv_stat_t* uv_fs_get_statbuf(uv_fs_t* req) Returns &req->statbuf. New in version 1.19.0. NINDENT SEE ALSO: NDENT 0.0 NDENT 3.5 The uv_req_t API functions also apply. NINDENT NINDENT
uv_os_fd_t uv_get_osfhandle(int fd) For a file descriptor in the C runtime, get the OS-dependent handle. On UNIX, returns the fd intact. On Windows, this calls \%_get_osfhandle. Note that the return value is still owned by the C runtime, any attempts to close it or to use it after closing the fd may lead to malfunction. NDENT 7.0 NDENT 3.5 New in version 1.12.0. NINDENT NINDENT NINDENT NDENT 0.0
int uv_open_osfhandle(uv_os_fd_t os_fd) For a OS-dependent handle, get the file descriptor in the C runtime. On UNIX, returns the os_fd intact. On Windows, this calls \%_open_osfhandle. Note that the return value is still owned by the CRT, any attempts to close it or to use it after closing the handle may lead to malfunction. NDENT 7.0 NDENT 3.5 New in version 1.23.0. NINDENT NINDENT NINDENT
UV_FS_O_APPEND The file is opened in append mode. Before each write, the file offset is positioned at the end of the file. NINDENT NDENT 0.0
UV_FS_O_CREAT The file is created if it does not already exist. NINDENT NDENT 0.0
UV_FS_O_DIRECT File I/O is done directly to and from user-space buffers, which must be aligned. Buffer size and address should be a multiple of the physical sector size of the block device. NOTE: NDENT 7.0 NDENT 3.5 UV_FS_O_DIRECT is supported on Linux, and on Windows via \%FILE_FLAG_NO_BUFFERING. UV_FS_O_DIRECT is not supported on macOS. NINDENT NINDENT NINDENT NDENT 0.0
UV_FS_O_DIRECTORY If the path is not a directory, fail the open. NOTE: NDENT 7.0 NDENT 3.5 UV_FS_O_DIRECTORY is not supported on Windows. NINDENT NINDENT NINDENT NDENT 0.0
UV_FS_O_DSYNC The file is opened for synchronous I/O. Write operations will complete once all data and a minimum of metadata are flushed to disk. NOTE: NDENT 7.0 NDENT 3.5 UV_FS_O_DSYNC is supported on Windows via \%FILE_FLAG_WRITE_THROUGH. NINDENT NINDENT NINDENT NDENT 0.0
UV_FS_O_EXCL If the O_CREAT flag is set and the file already exists, fail the open. NOTE: NDENT 7.0 NDENT 3.5 In general, the behavior of O_EXCL is undefined if it is used without O_CREAT. There is one exception: on Linux 2.6 and later, O_EXCL can be used without O_CREAT if pathname refers to a block device. If the block device is in use by the system (e.g., mounted), the open will fail with the error EBUSY. NINDENT NINDENT NINDENT NDENT 0.0
UV_FS_O_EXLOCK Atomically obtain an exclusive lock. NOTE: NDENT 7.0 NDENT 3.5 UV_FS_O_EXLOCK is only supported on macOS and Windows. NINDENT NINDENT Changed in version 1.17.0: support is added for Windows. NINDENT NDENT 0.0
UV_FS_O_FILEMAP Use a memory file mapping to access the file. When using this flag, the file cannot be open multiple times concurrently. NOTE: NDENT 7.0 NDENT 3.5 UV_FS_O_FILEMAP is only supported on Windows. NINDENT NINDENT NINDENT NDENT 0.0
UV_FS_O_NOATIME Do not update the file access time when the file is read. NOTE: NDENT 7.0 NDENT 3.5 UV_FS_O_NOATIME is not supported on Windows. NINDENT NINDENT NINDENT NDENT 0.0
UV_FS_O_NOCTTY If the path identifies a terminal device, opening the path will not cause that terminal to become the controlling terminal for the process (if the process does not already have one). NOTE: NDENT 7.0 NDENT 3.5 UV_FS_O_NOCTTY is not supported on Windows. NINDENT NINDENT NINDENT NDENT 0.0
UV_FS_O_NOFOLLOW If the path is a symbolic link, fail the open. NOTE: NDENT 7.0 NDENT 3.5 UV_FS_O_NOFOLLOW is not supported on Windows. NINDENT NINDENT NINDENT NDENT 0.0
UV_FS_O_NONBLOCK Open the file in nonblocking mode if possible. NOTE: NDENT 7.0 NDENT 3.5 UV_FS_O_NONBLOCK is not supported on Windows. NINDENT NINDENT NINDENT NDENT 0.0
UV_FS_O_RANDOM Access is intended to be random. The system can use this as a hint to optimize file caching. NOTE: NDENT 7.0 NDENT 3.5 UV_FS_O_RANDOM is only supported on Windows via \%FILE_FLAG_RANDOM_ACCESS. NINDENT NINDENT NINDENT NDENT 0.0
UV_FS_O_RDONLY Open the file for read-only access. NINDENT NDENT 0.0
UV_FS_O_RDWR Open the file for read-write access. NINDENT NDENT 0.0
UV_FS_O_SEQUENTIAL Access is intended to be sequential from beginning to end. The system can use this as a hint to optimize file caching. NOTE: NDENT 7.0 NDENT 3.5 UV_FS_O_SEQUENTIAL is only supported on Windows via \%FILE_FLAG_SEQUENTIAL_SCAN. NINDENT NINDENT NINDENT NDENT 0.0
UV_FS_O_SHORT_LIVED The file is temporary and should not be flushed to disk if possible. NOTE: NDENT 7.0 NDENT 3.5 UV_FS_O_SHORT_LIVED is only supported on Windows via \%FILE_ATTRIBUTE_TEMPORARY. NINDENT NINDENT NINDENT NDENT 0.0
UV_FS_O_SYMLINK Open the symbolic link itself rather than the resource it points to. NINDENT NDENT 0.0
UV_FS_O_SYNC The file is opened for synchronous I/O. Write operations will complete once all data and all metadata are flushed to disk. NOTE: NDENT 7.0 NDENT 3.5 UV_FS_O_SYNC is supported on Windows via \%FILE_FLAG_WRITE_THROUGH. NINDENT NINDENT NINDENT NDENT 0.0
UV_FS_O_TEMPORARY The file is temporary and should not be flushed to disk if possible. NOTE: NDENT 7.0 NDENT 3.5 UV_FS_O_TEMPORARY is only supported on Windows via \%FILE_ATTRIBUTE_TEMPORARY. NINDENT NINDENT NINDENT NDENT 0.0
UV_FS_O_TRUNC If the file exists and is a regular file, and the file is opened successfully for write access, its length shall be truncated to zero. NINDENT NDENT 0.0
UV_FS_O_WRONLY Open the file for write-only access. NINDENT
uv_work_t Work request type. NINDENT NDENT 0.0
void (*uv_work_cb)(uv_work_t* req) Callback passed to \%uv_queue_work() which will be run on the thread pool. NINDENT NDENT 0.0
void (*uv_after_work_cb)(uv_work_t* req, int status) Callback passed to \%uv_queue_work() which will be called on the loop thread after the work on the threadpool has been completed. If the work was cancelled using uv_cancel() status will be UV_ECANCELED. NINDENT
uv_loop_t* uv_work_t.loop Loop that started this request and where completion will be reported. Readonly. NINDENT SEE ALSO: NDENT 0.0 NDENT 3.5 The uv_req_t members also apply. NINDENT NINDENT
int uv_queue_work(uv_loop_t* loop, uv_work_t* req, uv_work_cb work_cb, uv_after_work_cb after_work_cb) Initializes a work request which will run the given work_cb in a thread from the threadpool. Once work_cb is completed, after_work_cb will be called on the loop thread. This request can be cancelled with uv_cancel(). NINDENT SEE ALSO: NDENT 0.0 NDENT 3.5 The uv_req_t API functions also apply. NINDENT NINDENT
uv_getaddrinfo_t getaddrinfo request type. NINDENT NDENT 0.0
void (*uv_getaddrinfo_cb)(uv_getaddrinfo_t* req, int status, struct addrinfo* res) Callback which will be called with the getaddrinfo request result once complete. In case it was cancelled, status will have a value of UV_ECANCELED. NINDENT NDENT 0.0
uv_getnameinfo_t getnameinfo request type. NINDENT NDENT 0.0
void (*uv_getnameinfo_cb)(uv_getnameinfo_t* req, int status, const char* hostname, const char* service) Callback which will be called with the getnameinfo request result once complete. In case it was cancelled, status will have a value of UV_ECANCELED. NINDENT
uv_loop_t* uv_getaddrinfo_t.loop Loop that started this getaddrinfo request and where completion will be reported. Readonly. NINDENT NDENT 0.0
struct addrinfo* uv_getaddrinfo_t.addrinfo Pointer to a struct addrinfo containing the result. Must be freed by the user with \%uv_freeaddrinfo(). Changed in version 1.3.0: the field is declared as public. NINDENT NDENT 0.0
uv_loop_t* uv_getnameinfo_t.loop Loop that started this getnameinfo request and where completion will be reported. Readonly. NINDENT NDENT 0.0
char[NI_MAXHOST] uv_getnameinfo_t.host Char array containing the resulting host. It\(aqs null terminated. Changed in version 1.3.0: the field is declared as public. NINDENT NDENT 0.0
char[NI_MAXSERV] uv_getnameinfo_t.service Char array containing the resulting service. It\(aqs null terminated. Changed in version 1.3.0: the field is declared as public. NINDENT SEE ALSO: NDENT 0.0 NDENT 3.5 The uv_req_t members also apply. NINDENT NINDENT
int uv_getaddrinfo(uv_loop_t* loop, uv_getaddrinfo_t* req, uv_getaddrinfo_cb getaddrinfo_cb, const char* node, const char* service, const struct addrinfo* hints) Asynchronous \%getaddrinfo(3). Either node or service may be NULL but not both. hints is a pointer to a struct addrinfo with additional address type constraints, or NULL. Consult man -s 3 getaddrinfo for more details. Returns 0 on success or an error code < 0 on failure. If successful, the callback will get called sometime in the future with the lookup result, which is either: NDENT 7.0
void uv_freeaddrinfo(struct addrinfo* ai) Free the struct addrinfo. Passing NULL is allowed and is a no-op. NINDENT NDENT 0.0
int uv_getnameinfo(uv_loop_t* loop, uv_getnameinfo_t* req, uv_getnameinfo_cb getnameinfo_cb, const struct sockaddr* addr, int flags) Asynchronous \%getnameinfo(3). Returns 0 on success or an error code < 0 on failure. If successful, the callback will get called sometime in the future with the lookup result. Consult man -s 3 getnameinfo for more details. Changed in version 1.3.0: the callback parameter is now allowed to be NULL, in which case the request will run synchronously. NINDENT SEE ALSO: NDENT 0.0 NDENT 3.5 The uv_req_t API functions also apply. NINDENT NINDENT
uv_lib_t Shared library data type. NINDENT
int uv_dlopen(const char* filename, uv_lib_t* lib) Opens a shared library. The filename is in utf-8. Returns 0 on success and -1 on error. Call \%uv_dlerror() to get the error message. NINDENT NDENT 0.0
void uv_dlclose(uv_lib_t* lib) Close the shared library. NINDENT NDENT 0.0
int uv_dlsym(uv_lib_t* lib, const char* name, void** ptr) Retrieves a data pointer from a dynamic library. It is legal for a symbol to map to NULL. Returns 0 on success and -1 if the symbol was not found. NINDENT NDENT 0.0
const char* uv_dlerror(const uv_lib_t* lib) Returns the last uv_dlopen() or uv_dlsym() error message. NINDENT
uv_thread_t Thread data type. NINDENT NDENT 0.0
void (*uv_thread_cb)(void* arg) Callback that is invoked to initialize thread execution. arg is the same value that was passed to \%uv_thread_create(). NINDENT NDENT 0.0
uv_key_t Thread-local key data type. NINDENT NDENT 0.0
uv_once_t Once-only initializer data type. NINDENT NDENT 0.0
uv_mutex_t Mutex data type. NINDENT NDENT 0.0
uv_rwlock_t Read-write lock data type. NINDENT NDENT 0.0
uv_sem_t Semaphore data type. NINDENT NDENT 0.0
uv_cond_t Condition data type. NINDENT NDENT 0.0
uv_barrier_t Barrier data type. NINDENT
uv_thread_options_t Options for spawning a new thread (passed to \%uv_thread_create_ex()). NDENT 7.0 NDENT 3.5
typedef struct uv_thread_options_s { enum { UV_THREAD_NO_FLAGS = 0x00, UV_THREAD_HAS_STACK_SIZE = 0x01 } flags; size_t stack_size; } uv_thread_options_t;NINDENT NINDENT More fields may be added to this struct at any time, so its exact layout and size should not be relied upon. New in version 1.26.0. NINDENT NDENT 0.0
int uv_thread_create(uv_thread_t* tid, uv_thread_cb entry, void* arg) Changed in version 1.4.1: returns a UV_E* error code on failure NINDENT NDENT 0.0
int uv_thread_create_ex(uv_thread_t* tid, const uv_thread_options_t* params, uv_thread_cb entry, void* arg) Like \%uv_thread_create(), but additionally specifies options for creating a new thread. If UV_THREAD_HAS_STACK_SIZE is set, stack_size specifies a stack size for the new thread. 0 indicates that the default value should be used, i.e. behaves as if the flag was not set. Other values will be rounded up to the nearest page boundary. New in version 1.26.0. NINDENT NDENT 0.0
uv_thread_t uv_thread_self(void) NINDENT NDENT 0.0
int uv_thread_join(uv_thread_t *tid) NINDENT NDENT 0.0
int uv_thread_equal(const uv_thread_t* t1, const uv_thread_t* t2) NINDENT
int uv_key_create(uv_key_t* key) NINDENT NDENT 0.0
void uv_key_delete(uv_key_t* key) NINDENT NDENT 0.0
void* uv_key_get(uv_key_t* key) NINDENT NDENT 0.0
void uv_key_set(uv_key_t* key, void* value) NINDENT
void uv_once(uv_once_t* guard, void (*callback)(void)) NINDENT
int uv_mutex_init(uv_mutex_t* handle) NINDENT NDENT 0.0
int uv_mutex_init_recursive(uv_mutex_t* handle) NINDENT NDENT 0.0
void uv_mutex_destroy(uv_mutex_t* handle) NINDENT NDENT 0.0
void uv_mutex_lock(uv_mutex_t* handle) NINDENT NDENT 0.0
int uv_mutex_trylock(uv_mutex_t* handle) NINDENT NDENT 0.0
void uv_mutex_unlock(uv_mutex_t* handle) NINDENT
int uv_rwlock_init(uv_rwlock_t* rwlock) NINDENT NDENT 0.0
void uv_rwlock_destroy(uv_rwlock_t* rwlock) NINDENT NDENT 0.0
void uv_rwlock_rdlock(uv_rwlock_t* rwlock) NINDENT NDENT 0.0
int uv_rwlock_tryrdlock(uv_rwlock_t* rwlock) NINDENT NDENT 0.0
void uv_rwlock_rdunlock(uv_rwlock_t* rwlock) NINDENT NDENT 0.0
void uv_rwlock_wrlock(uv_rwlock_t* rwlock) NINDENT NDENT 0.0
int uv_rwlock_trywrlock(uv_rwlock_t* rwlock) NINDENT NDENT 0.0
void uv_rwlock_wrunlock(uv_rwlock_t* rwlock) NINDENT
int uv_sem_init(uv_sem_t* sem, unsigned int value) NINDENT NDENT 0.0
void uv_sem_destroy(uv_sem_t* sem) NINDENT NDENT 0.0
void uv_sem_post(uv_sem_t* sem) NINDENT NDENT 0.0
void uv_sem_wait(uv_sem_t* sem) NINDENT NDENT 0.0
int uv_sem_trywait(uv_sem_t* sem) NINDENT
int uv_cond_init(uv_cond_t* cond) NINDENT NDENT 0.0
void uv_cond_destroy(uv_cond_t* cond) NINDENT NDENT 0.0
void uv_cond_signal(uv_cond_t* cond) NINDENT NDENT 0.0
void uv_cond_broadcast(uv_cond_t* cond) NINDENT NDENT 0.0
void uv_cond_wait(uv_cond_t* cond, uv_mutex_t* mutex) NINDENT NDENT 0.0
int uv_cond_timedwait(uv_cond_t* cond, uv_mutex_t* mutex, uint64_t timeout) NINDENT
if (uv_barrier_wait(&barrier) > 0) uv_barrier_destroy(&barrier);NINDENT NINDENT NINDENT NINDENT NDENT 0.0
int uv_barrier_init(uv_barrier_t* barrier, unsigned int count) NINDENT NDENT 0.0
void uv_barrier_destroy(uv_barrier_t* barrier) NINDENT NDENT 0.0
int uv_barrier_wait(uv_barrier_t* barrier) NINDENT
uv_buf_t Buffer data type. NDENT 7.0
char* uv_buf_t.base Pointer to the base of the buffer. NINDENT NDENT 7.0
size_t uv_buf_t.len Total bytes in the buffer. NOTE: NDENT 7.0 NDENT 3.5 On Windows this field is ULONG. NINDENT NINDENT NINDENT NINDENT NDENT 0.0
void* (*uv_malloc_func)(size_t size) Replacement function for \%malloc(3). See \%uv_replace_allocator(). NINDENT NDENT 0.0
void* (*uv_realloc_func)(void* ptr, size_t size) Replacement function for \%realloc(3). See \%uv_replace_allocator(). NINDENT NDENT 0.0
void* (*uv_calloc_func)(size_t count, size_t size) Replacement function for \%calloc(3). See \%uv_replace_allocator(). NINDENT NDENT 0.0
void (*uv_free_func)(void* ptr) Replacement function for \%free(3). See \%uv_replace_allocator(). NINDENT NDENT 0.0
void (*uv_random_cb)(uv_random_t* req, int status, void* buf, size_t buflen) Callback passed to \%uv_random(). status is non-zero in case of error. The buf pointer is the same pointer that was passed to \%uv_random(). NINDENT NDENT 0.0
uv_file Cross platform representation of a file handle. NINDENT NDENT 0.0
uv_os_sock_t Cross platform representation of a socket handle. NINDENT NDENT 0.0
uv_os_fd_t Abstract representation of a file descriptor. On Unix systems this is a typedef of int and on Windows a HANDLE. NINDENT NDENT 0.0
uv_pid_t Cross platform representation of a pid_t. New in version 1.16.0. NINDENT NDENT 0.0
uv_timeval_t Data type for storing times. NDENT 7.0 NDENT 3.5
typedef struct { long tv_sec; long tv_usec; } uv_timeval_t;NINDENT NINDENT NINDENT NDENT 0.0
uv_timeval64_t Alternative data type for storing times. NDENT 7.0 NDENT 3.5
typedef struct { int64_t tv_sec; int32_t tv_usec; } uv_timeval64_t;NINDENT NINDENT NINDENT NDENT 0.0
uv_rusage_t Data type for resource usage results. NDENT 7.0 NDENT 3.5
typedef struct { uv_timeval_t ru_utime; /* user CPU time used */ uv_timeval_t ru_stime; /* system CPU time used */ uint64_t ru_maxrss; /* maximum resident set size */ uint64_t ru_ixrss; /* integral shared memory size (X) */ uint64_t ru_idrss; /* integral unshared data size (X) */ uint64_t ru_isrss; /* integral unshared stack size (X) */ uint64_t ru_minflt; /* page reclaims (soft page faults) (X) */ uint64_t ru_majflt; /* page faults (hard page faults) */ uint64_t ru_nswap; /* swaps (X) */ uint64_t ru_inblock; /* block input operations */ uint64_t ru_oublock; /* block output operations */ uint64_t ru_msgsnd; /* IPC messages sent (X) */ uint64_t ru_msgrcv; /* IPC messages received (X) */ uint64_t ru_nsignals; /* signals received (X) */ uint64_t ru_nvcsw; /* voluntary context switches (X) */ uint64_t ru_nivcsw; /* involuntary context switches (X) */ } uv_rusage_t;NINDENT NINDENT Members marked with (X) are unsupported on Windows. See \%getrusage(2) for supported fields on Unix NINDENT NDENT 0.0
uv_cpu_info_t Data type for CPU information. NDENT 7.0 NDENT 3.5
typedef struct uv_cpu_info_s { char* model; int speed; struct uv_cpu_times_s { uint64_t user; /* milliseconds */ uint64_t nice; /* milliseconds */ uint64_t sys; /* milliseconds */ uint64_t idle; /* milliseconds */ uint64_t irq; /* milliseconds */ } cpu_times; } uv_cpu_info_t;NINDENT NINDENT NINDENT NDENT 0.0
uv_interface_address_t Data type for interface addresses. NDENT 7.0 NDENT 3.5
typedef struct uv_interface_address_s { char* name; char phys_addr[6]; int is_internal; union { struct sockaddr_in address4; struct sockaddr_in6 address6; } address; union { struct sockaddr_in netmask4; struct sockaddr_in6 netmask6; } netmask; } uv_interface_address_t;NINDENT NINDENT NINDENT NDENT 0.0
uv_passwd_t Data type for password file information. NDENT 7.0 NDENT 3.5
typedef struct uv_passwd_s { char* username; long uid; long gid; char* shell; char* homedir; } uv_passwd_t;NINDENT NINDENT NINDENT NDENT 0.0
uv_utsname_t Data type for operating system name and version information. NDENT 7.0 NDENT 3.5
typedef struct uv_utsname_s { char sysname[256]; char release[256]; char version[256]; char machine[256]; } uv_utsname_t;NINDENT NINDENT NINDENT NDENT 0.0
uv_env_item_t Data type for environment variable storage. NDENT 7.0 NDENT 3.5
typedef struct uv_env_item_s { char* name; char* value; } uv_env_item_t;NINDENT NINDENT NINDENT NDENT 0.0
uv_random_t Random data request type. NINDENT
uv_handle_type uv_guess_handle(uv_file file) Used to detect what type of stream should be used with a given file descriptor. Usually this will be used during initialization to guess the type of the stdio streams. For \%isatty(3) equivalent functionality use this function and test for UV_TTY. NINDENT NDENT 0.0
int uv_replace_allocator(uv_malloc_func malloc_func, uv_realloc_func realloc_func, uv_calloc_func calloc_func, uv_free_func free_func) New in version 1.6.0. Override the use of the standard library\(aqs \%malloc(3), \%calloc(3), \%realloc(3), \%free(3), memory allocation functions. This function must be called before any other libuv function is called or after all resources have been freed and thus libuv doesn\(aqt reference any allocated memory chunk. On success, it returns 0, if any of the function pointers is NULL it returns UV_EINVAL. WARNING: NDENT 7.0 NDENT 3.5 There is no protection against changing the allocator multiple times. If the user changes it they are responsible for making sure the allocator is changed while no memory was allocated with the previous allocator, or that they are compatible. NINDENT NINDENT WARNING: NDENT 7.0 NDENT 3.5 Allocator must be thread-safe. NINDENT NINDENT NINDENT NDENT 0.0
void uv_library_shutdown(void); New in version 1.38.0. Release any global state that libuv is holding onto. Libuv will normally do so automatically when it is unloaded but it can be instructed to perform cleanup manually. WARNING: NDENT 7.0 NDENT 3.5 Only call uv_library_shutdown() once. NINDENT NINDENT WARNING: NDENT 7.0 NDENT 3.5 Don\(aqt call uv_library_shutdown() when there are still event loops or I/O requests active. NINDENT NINDENT WARNING: NDENT 7.0 NDENT 3.5 Don\(aqt call libuv functions after calling uv_library_shutdown(). NINDENT NINDENT NINDENT NDENT 0.0
uv_buf_t uv_buf_init(char* base, unsigned int len) Constructor for \%uv_buf_t. Due to platform differences the user cannot rely on the ordering of the base and len members of the uv_buf_t struct. The user is responsible for freeing base after the uv_buf_t is done. Return struct passed by value. NINDENT NDENT 0.0
char** uv_setup_args(int argc, char** argv) Store the program arguments. Required for getting / setting the process title. Libuv may take ownership of the memory that argv points to. This function should be called exactly once, at program start-up. Example: NDENT 7.0 NDENT 3.5
argv = uv_setup_args(argc, argv); /* May return a copy of argv. */NINDENT NINDENT NINDENT NDENT 0.0
int uv_get_process_title(char* buffer, size_t size) Gets the title of the current process. You must call uv_setup_args before calling this function. If buffer is NULL or size is zero, UV_EINVAL is returned. If size cannot accommodate the process title and terminating NULL character, the function returns UV_ENOBUFS. Changed in version 1.18.1: now thread-safe on all supported platforms. NINDENT NDENT 0.0
int uv_set_process_title(const char* title) Sets the current process title. You must call uv_setup_args before calling this function. On platforms with a fixed size buffer for the process title the contents of title will be copied to the buffer and truncated if larger than the available space. Other platforms will return UV_ENOMEM if they cannot allocate enough space to duplicate the contents of title. Changed in version 1.18.1: now thread-safe on all supported platforms. NINDENT NDENT 0.0
int uv_resident_set_memory(size_t* rss) Gets the resident set size (RSS) for the current process. NINDENT NDENT 0.0
int uv_uptime(double* uptime) Gets the current system uptime. NINDENT NDENT 0.0
int uv_getrusage(uv_rusage_t* rusage) Gets the resource usage measures for the current process. NOTE: NDENT 7.0 NDENT 3.5 On Windows not all fields are set, the unsupported fields are filled with zeroes. See \%uv_rusage_t for more details. NINDENT NINDENT NINDENT NDENT 0.0
uv_pid_t uv_os_getpid(void) Returns the current process ID. New in version 1.18.0. NINDENT NDENT 0.0
uv_pid_t uv_os_getppid(void) Returns the parent process ID. New in version 1.16.0. NINDENT NDENT 0.0
int uv_cpu_info(uv_cpu_info_t** cpu_infos, int* count) Gets information about the CPUs on the system. The cpu_infos array will have count elements and needs to be freed with \%uv_free_cpu_info(). NINDENT NDENT 0.0
void uv_free_cpu_info(uv_cpu_info_t* cpu_infos, int count) Frees the cpu_infos array previously allocated with \%uv_cpu_info(). NINDENT NDENT 0.0
int uv_interface_addresses(uv_interface_address_t** addresses, int* count) Gets address information about the network interfaces on the system. An array of count elements is allocated and returned in addresses. It must be freed by the user, calling \%uv_free_interface_addresses(). NINDENT NDENT 0.0
void uv_free_interface_addresses(uv_interface_address_t* addresses, int count) Free an array of \%uv_interface_address_t which was returned by \%uv_interface_addresses(). NINDENT NDENT 0.0
void uv_loadavg(double avg[3]) Gets the load average. See: \%https://en.wikipedia.org/wiki/Load_(computing) NOTE: NDENT 7.0 NDENT 3.5 Returns [0,0,0] on Windows (i.e., it\(aqs not implemented). NINDENT NINDENT NINDENT NDENT 0.0
int uv_ip4_addr(const char* ip, int port, struct sockaddr_in* addr) Convert a string containing an IPv4 addresses to a binary structure. NINDENT NDENT 0.0
int uv_ip6_addr(const char* ip, int port, struct sockaddr_in6* addr) Convert a string containing an IPv6 addresses to a binary structure. NINDENT NDENT 0.0
int uv_ip4_name(const struct sockaddr_in* src, char* dst, size_t size) Convert a binary structure containing an IPv4 address to a string. NINDENT NDENT 0.0
int uv_ip6_name(const struct sockaddr_in6* src, char* dst, size_t size) Convert a binary structure containing an IPv6 address to a string. NINDENT NDENT 0.0
int uv_inet_ntop(int af, const void* src, char* dst, size_t size) NINDENT NDENT 0.0
int uv_inet_pton(int af, const char* src, void* dst) Cross-platform IPv6-capable implementation of \%inet_ntop(3) and \%inet_pton(3). On success they return 0. In case of error the target dst pointer is unmodified. NINDENT NDENT 0.0
UV_IF_NAMESIZE Maximum IPv6 interface identifier name length. Defined as IFNAMSIZ on Unix and IF_NAMESIZE on Linux and Windows. New in version 1.16.0. NINDENT NDENT 0.0
int uv_if_indextoname(unsigned int ifindex, char* buffer, size_t* size) IPv6-capable implementation of \%if_indextoname(3). When called, *size indicates the length of the buffer, which is used to store the result. On success, zero is returned, buffer contains the interface name, and *size represents the string length of the buffer, excluding the NUL terminator byte from *size. On error, a negative result is returned. If buffer is not large enough to hold the result, UV_ENOBUFS is returned, and *size represents the necessary size in bytes, including the NUL terminator byte into the *size. On Unix, the returned interface name can be used directly as an interface identifier in scoped IPv6 addresses, e.g. fe80::abc:def1:2345%en0. On Windows, the returned interface cannot be used as an interface identifier, as Windows uses numerical interface identifiers, e.g. fe80::abc:def1:2345%5. To get an interface identifier in a cross-platform compatible way, use uv_if_indextoiid(). Example: NDENT 7.0 NDENT 3.5
char ifname[UV_IF_NAMESIZE]; size_t size = sizeof(ifname); uv_if_indextoname(sin6->sin6_scope_id, ifname, &size);NINDENT NINDENT New in version 1.16.0. NINDENT NDENT 0.0
int uv_if_indextoiid(unsigned int ifindex, char* buffer, size_t* size) Retrieves a network interface identifier suitable for use in an IPv6 scoped address. On Windows, returns the numeric ifindex as a string. On all other platforms, uv_if_indextoname() is called. The result is written to buffer, with *size indicating the length of buffer. If buffer is not large enough to hold the result, then UV_ENOBUFS is returned, and *size represents the size, including the NUL byte, required to hold the result. See uv_if_indextoname for further details. New in version 1.16.0. NINDENT NDENT 0.0
int uv_exepath(char* buffer, size_t* size) Gets the executable path. NINDENT NDENT 0.0
int uv_cwd(char* buffer, size_t* size) Gets the current working directory, and stores it in buffer. If the current working directory is too large to fit in buffer, this function returns UV_ENOBUFS, and sets size to the required length, including the null terminator. Changed in version 1.1.0: On Unix the path no longer ends in a slash. Changed in version 1.9.0: the returned length includes the terminating null byte on UV_ENOBUFS, and the buffer is null terminated on success. NINDENT NDENT 0.0
int uv_chdir(const char* dir) Changes the current working directory. NINDENT NDENT 0.0
int uv_os_homedir(char* buffer, size_t* size) Gets the current user\(aqs home directory. On Windows, uv_os_homedir() first checks the USERPROFILE environment variable using GetEnvironmentVariableW(). If USERPROFILE is not set, GetUserProfileDirectoryW() is called. On all other operating systems, uv_os_homedir() first checks the HOME environment variable using \%getenv(3). If HOME is not set, \%getpwuid_r(3) is called. The user\(aqs home directory is stored in buffer. When uv_os_homedir() is called, size indicates the maximum size of buffer. On success size is set to the string length of buffer. On UV_ENOBUFS failure size is set to the required length for buffer, including the null byte. WARNING: NDENT 7.0 NDENT 3.5 uv_os_homedir() is not thread safe. NINDENT NINDENT New in version 1.6.0. NINDENT NDENT 0.0
int uv_os_tmpdir(char* buffer, size_t* size) Gets the temp directory. On Windows, uv_os_tmpdir() uses GetTempPathW(). On all other operating systems, uv_os_tmpdir() uses the first environment variable found in the ordered list TMPDIR, TMP, TEMP, and TEMPDIR. If none of these are found, the path "/tmp" is used, or, on Android, "/data/local/tmp" is used. The temp directory is stored in buffer. When uv_os_tmpdir() is called, size indicates the maximum size of buffer. On success size is set to the string length of buffer (which does not include the terminating null). On UV_ENOBUFS failure size is set to the required length for buffer, including the null byte. WARNING: NDENT 7.0 NDENT 3.5 uv_os_tmpdir() is not thread safe. NINDENT NINDENT New in version 1.9.0. NINDENT NDENT 0.0
int uv_os_get_passwd(uv_passwd_t* pwd) Gets a subset of the password file entry for the current effective uid (not the real uid). The populated data includes the username, euid, gid, shell, and home directory. On non-Windows systems, all data comes from \%getpwuid_r(3). On Windows, uid and gid are set to -1 and have no meaning, and shell is NULL. After successfully calling this function, the memory allocated to pwd needs to be freed with \%uv_os_free_passwd(). New in version 1.9.0. NINDENT NDENT 0.0
void uv_os_free_passwd(uv_passwd_t* pwd) Frees the pwd memory previously allocated with \%uv_os_get_passwd(). New in version 1.9.0. NINDENT NDENT 0.0
uint64_t uv_get_free_memory(void) Gets memory information (in bytes). NINDENT NDENT 0.0
uint64_t uv_get_total_memory(void) Gets memory information (in bytes). NINDENT NDENT 0.0
uint64_t uv_get_constrained_memory(void) Gets the amount of memory available to the process (in bytes) based on limits imposed by the OS. If there is no such constraint, or the constraint is unknown, 0 is returned. Note that it is not unusual for this value to be less than or greater than \%uv_get_total_memory(). NOTE: NDENT 7.0 NDENT 3.5 This function currently only returns a non-zero value on Linux, based on cgroups if it is present. NINDENT NINDENT New in version 1.29.0. NINDENT NDENT 0.0
uint64_t uv_hrtime(void) Returns the current high-resolution real time. This is expressed in nanoseconds. It is relative to an arbitrary time in the past. It is not related to the time of day and therefore not subject to clock drift. The primary use is for measuring performance between intervals. NOTE: NDENT 7.0 NDENT 3.5 Not every platform can support nanosecond resolution; however, this value will always be in nanoseconds. NINDENT NINDENT NINDENT NDENT 0.0
void uv_print_all_handles(uv_loop_t* loop, FILE* stream) Prints all handles associated with the given loop to the given stream. Example: NDENT 7.0 NDENT 3.5
uv_print_all_handles(uv_default_loop(), stderr); /* [--I] signal 0x1a25ea8 [-AI] async 0x1a25cf0 [R--] idle 0x1a7a8c8 */NINDENT NINDENT The format is [flags] handle-type handle-address. For flags: NDENT 7.0
void uv_print_active_handles(uv_loop_t* loop, FILE* stream) This is the same as \%uv_print_all_handles() except only active handles are printed. WARNING: NDENT 7.0 NDENT 3.5 This function is meant for ad hoc debugging, there is no API/ABI stability guarantees. NINDENT NINDENT New in version 1.8.0. NINDENT NDENT 0.0
int uv_os_environ(uv_env_item_t** envitems, int* count) Retrieves all environment variables. This function will allocate memory which must be freed by calling uv_os_free_environ(). WARNING: NDENT 7.0 NDENT 3.5 This function is not thread safe. NINDENT NINDENT New in version 1.31.0. NINDENT NDENT 0.0
void uv_os_free_environ(uv_env_item_t* envitems, int count); Frees the memory allocated for the environment variables by \%uv_os_environ(). New in version 1.31.0. NINDENT NDENT 0.0
int uv_os_getenv(const char* name, char* buffer, size_t* size) Retrieves the environment variable specified by name, copies its value into buffer, and sets size to the string length of the value. When calling this function, size must be set to the amount of storage available in buffer, including the null terminator. If the environment variable exceeds the storage available in buffer, UV_ENOBUFS is returned, and size is set to the amount of storage required to hold the value. If no matching environment variable exists, UV_ENOENT is returned. WARNING: NDENT 7.0 NDENT 3.5 This function is not thread safe. NINDENT NINDENT New in version 1.12.0. NINDENT NDENT 0.0
int uv_os_setenv(const char* name, const char* value) Creates or updates the environment variable specified by name with value. WARNING: NDENT 7.0 NDENT 3.5 This function is not thread safe. NINDENT NINDENT New in version 1.12.0. NINDENT NDENT 0.0
int uv_os_unsetenv(const char* name) Deletes the environment variable specified by name. If no such environment variable exists, this function returns successfully. WARNING: NDENT 7.0 NDENT 3.5 This function is not thread safe. NINDENT NINDENT New in version 1.12.0. NINDENT NDENT 0.0
int uv_os_gethostname(char* buffer, size_t* size) Returns the hostname as a null-terminated string in buffer, and sets size to the string length of the hostname. When calling this function, size must be set to the amount of storage available in buffer, including the null terminator. If the hostname exceeds the storage available in buffer, UV_ENOBUFS is returned, and size is set to the amount of storage required to hold the value. New in version 1.12.0. Changed in version 1.26.0: UV_MAXHOSTNAMESIZE is available and represents the maximum buffer size required to store a hostname and terminating nul character. NINDENT NDENT 0.0
int uv_os_getpriority(uv_pid_t pid, int* priority) Retrieves the scheduling priority of the process specified by pid. The returned value of priority is between -20 (high priority) and 19 (low priority). NOTE: NDENT 7.0 NDENT 3.5 On Windows, the returned priority will equal one of the UV_PRIORITY constants. NINDENT NINDENT New in version 1.23.0. NINDENT NDENT 0.0
int uv_os_setpriority(uv_pid_t pid, int priority) Sets the scheduling priority of the process specified by pid. The priority value range is between -20 (high priority) and 19 (low priority). The constants UV_PRIORITY_LOW, UV_PRIORITY_BELOW_NORMAL, UV_PRIORITY_NORMAL, UV_PRIORITY_ABOVE_NORMAL, UV_PRIORITY_HIGH, and UV_PRIORITY_HIGHEST are also provided for convenience. NOTE: NDENT 7.0 NDENT 3.5 On Windows, this function utilizes SetPriorityClass(). The priority argument is mapped to a Windows priority class. When retrieving the process priority, the result will equal one of the UV_PRIORITY constants, and not necessarily the exact value of priority. NINDENT NINDENT NOTE: NDENT 7.0 NDENT 3.5 On Windows, setting PRIORITY_HIGHEST will only work for elevated user, for others it will be silently reduced to PRIORITY_HIGH. NINDENT NINDENT NOTE: NDENT 7.0 NDENT 3.5 On IBM i PASE, the highest process priority is -10. The constant UV_PRIORITY_HIGHEST is -10, UV_PRIORITY_HIGH is -7, UV_PRIORITY_ABOVE_NORMAL is -4, UV_PRIORITY_NORMAL is 0, UV_PRIORITY_BELOW_NORMAL is 15 and UV_PRIORITY_LOW is 39. NINDENT NINDENT NOTE: NDENT 7.0 NDENT 3.5 On IBM i PASE, you are not allowed to change your priority unless you have the *JOBCTL special authority (even to lower it). NINDENT NINDENT New in version 1.23.0. NINDENT NDENT 0.0
int uv_os_uname(uv_utsname_t* buffer) Retrieves system information in buffer. The populated data includes the operating system name, release, version, and machine. On non-Windows systems, uv_os_uname() is a thin wrapper around \%uname(2). Returns zero on success, and a non-zero error value otherwise. New in version 1.25.0. NINDENT NDENT 0.0
int uv_gettimeofday(uv_timeval64_t* tv) Cross-platform implementation of \%gettimeofday(2). The timezone argument to gettimeofday() is not supported, as it is considered obsolete. New in version 1.28.0. NINDENT NDENT 0.0
int uv_random(uv_loop_t* loop, uv_random_t* req, void* buf, size_t buflen, unsigned int flags, uv_random_cb cb) Fill buf with exactly buflen cryptographically strong random bytes acquired from the system CSPRNG. flags is reserved for future extension and must currently be 0. Short reads are not possible. When less than buflen random bytes are available, a non-zero error value is returned or passed to the callback. The synchronous version may block indefinitely when not enough entropy is available. The asynchronous version may not ever finish when the system is low on entropy. Sources of entropy: NDENT 7.0
Returns 0 on success, or an error code < 0 on failure. The contents of buf is undefined after an error. NINDENT NOTE: NDENT 7.0 NDENT 3.5 When using the synchronous version, both loop and req parameters are not used and can be set to NULL. NINDENT NINDENT New in version 1.33.0. NINDENT NDENT 0.0
void uv_sleep(unsigned int msec) Causes the calling thread to sleep for msec milliseconds. New in version 1.34.0. NINDENT
cd libuv ./autogen.sh ./configure makeNINDENT NINDENT There is no need to make install. To build the examples run make in the code/ directory.
while there are still events to process: e = get the next event if there is a callback associated with e: call the callbackNINDENT NINDENT Some examples of events are: NDENT 0.0
#include <stdio.h> #include <stdlib.h> #include <uv.h> int main() { uv_loop_t *loop = malloc(sizeof(uv_loop_t)); uv_loop_init(loop); printf("Now quitting.\en"); uv_run(loop, UV_RUN_DEFAULT); uv_loop_close(loop); free(loop); return 0; }NINDENT NINDENT This program quits immediately because it has no events to process. A libuv event loop has to be told to watch out for events using the various API functions. Starting with libuv v1.0, users should allocate the memory for the loops before initializing it with uv_loop_init(uv_loop_t *). This allows you to plug in custom memory management. Remember to de-initialize the loop using uv_loop_close(uv_loop_t *) and then delete the storage. The examples never close loops since the program quits after the loop ends and the system will reclaim memory. Production grade projects, especially long running systems programs, should take care to release correctly.
/* Handle types. */ typedef struct uv_loop_s uv_loop_t; typedef struct uv_handle_s uv_handle_t; typedef struct uv_dir_s uv_dir_t; typedef struct uv_stream_s uv_stream_t; typedef struct uv_tcp_s uv_tcp_t; typedef struct uv_udp_s uv_udp_t; typedef struct uv_pipe_s uv_pipe_t; typedef struct uv_tty_s uv_tty_t; typedef struct uv_poll_s uv_poll_t; typedef struct uv_timer_s uv_timer_t; typedef struct uv_prepare_s uv_prepare_t; typedef struct uv_check_s uv_check_t; typedef struct uv_idle_s uv_idle_t; typedef struct uv_async_s uv_async_t; typedef struct uv_process_s uv_process_t; typedef struct uv_fs_event_s uv_fs_event_t; typedef struct uv_fs_poll_s uv_fs_poll_t; typedef struct uv_signal_s uv_signal_t; /* Request types. */ typedef struct uv_req_s uv_req_t; typedef struct uv_getaddrinfo_s uv_getaddrinfo_t; typedef struct uv_getnameinfo_s uv_getnameinfo_t; typedef struct uv_shutdown_s uv_shutdown_t; typedef struct uv_write_s uv_write_t; typedef struct uv_connect_s uv_connect_t; typedef struct uv_udp_send_s uv_udp_send_t; typedef struct uv_fs_s uv_fs_t; typedef struct uv_work_s uv_work_t;NINDENT NINDENT Handles represent long-lived objects. Async operations on such handles are identified using requests. A request is short-lived (usually used across only one callback) and usually indicates one I/O operation on a handle. Requests are used to preserve context between the initiation and the callback of individual actions. For example, an UDP socket is represented by a uv_udp_t, while individual writes to the socket use a uv_udp_send_t structure that is passed to the callback after the write is done. Handles are setup by a corresponding: NDENT 0.0 NDENT 3.5
uv_TYPE_init(uv_loop_t *, uv_TYPE_t *)NINDENT NINDENT function. Callbacks are functions which are called by libuv whenever an event the watcher is interested in has taken place. Application specific logic will usually be implemented in the callback. For example, an IO watcher\(aqs callback will receive the data read from a file, a timer callback will be triggered on timeout and so on.
#include <stdio.h> #include <uv.h> int64_t counter = 0; void wait_for_a_while(uv_idle_t* handle) { counter++; if (counter >= 10e6) uv_idle_stop(handle); } int main() { uv_idle_t idler; uv_idle_init(uv_default_loop(), &idler); uv_idle_start(&idler, wait_for_a_while); printf("Idling...\en"); uv_run(uv_default_loop(), UV_RUN_DEFAULT); uv_loop_close(uv_default_loop()); return 0; }NINDENT NINDENT
----
0
int uv_fs_open(uv_loop_t* loop, uv_fs_t* req, const char* path, int flags, int mode, uv_fs_cb cb)NINDENT NINDENT flags and mode are standard \%Unix flags. libuv takes care of converting to the appropriate Windows flags. File descriptors are closed using NDENT 0.0 NDENT 3.5
int uv_fs_close(uv_loop_t* loop, uv_fs_t* req, uv_file file, uv_fs_cb cb)NINDENT NINDENT Filesystem operation callbacks have the signature: NDENT 0.0 NDENT 3.5
void callback(uv_fs_t* req);NINDENT NINDENT Let\(aqs see a simple implementation of cat. We start with registering a callback for when the file is opened: uvcat/main.c - opening a file NDENT 0.0 NDENT 3.5
void on_open(uv_fs_t *req) { // The request passed to the callback is the same as the one the call setup // function was passed. assert(req == &open_req); if (req->result >= 0) { iov = uv_buf_init(buffer, sizeof(buffer)); uv_fs_read(uv_default_loop(), &read_req, req->result, &iov, 1, -1, on_read); } else { fprintf(stderr, "error opening file: %s\en", uv_strerror((int)req->result)); } }NINDENT NINDENT The result field of a uv_fs_t is the file descriptor in case of the uv_fs_open callback. If the file is successfully opened, we start reading it. uvcat/main.c - read callback NDENT 0.0 NDENT 3.5
void on_read(uv_fs_t *req) { if (req->result < 0) { fprintf(stderr, "Read error: %s\en", uv_strerror(req->result)); } else if (req->result == 0) { uv_fs_t close_req; // synchronous uv_fs_close(uv_default_loop(), &close_req, open_req.result, NULL); } else if (req->result > 0) { iov.len = req->result; uv_fs_write(uv_default_loop(), &write_req, 1, &iov, 1, -1, on_write); } }NINDENT NINDENT In the case of a read call, you should pass an initialized buffer which will be filled with data before the read callback is triggered. The uv_fs_* operations map almost directly to certain POSIX functions, so EOF is indicated in this case by result being 0. In the case of streams or pipes, the UV_EOF constant would have been passed as a status instead. Here you see a common pattern when writing asynchronous programs. The uv_fs_close() call is performed synchronously. Usually tasks which are one-off, or are done as part of the startup or shutdown stage are performed synchronously, since we are interested in fast I/O when the program is going about its primary task and dealing with multiple I/O sources. For solo tasks the performance difference usually is negligible and may lead to simpler code. Filesystem writing is similarly simple using uv_fs_write(). Your callback will be triggered after the write is complete. In our case the callback simply drives the next read. Thus read and write proceed in lockstep via callbacks. uvcat/main.c - write callback NDENT 0.0 NDENT 3.5
void on_write(uv_fs_t *req) { if (req->result < 0) { fprintf(stderr, "Write error: %s\en", uv_strerror((int)req->result)); } else { uv_fs_read(uv_default_loop(), &read_req, open_req.result, &iov, 1, -1, on_read); } }NINDENT NINDENT WARNING: NDENT 0.0 NDENT 3.5 Due to the way filesystems and disk drives are configured for performance, a write that \(aqsucceeds\(aq may not be committed to disk yet. NINDENT NINDENT We set the dominos rolling in main(): uvcat/main.c NDENT 0.0 NDENT 3.5
int main(int argc, char **argv) { uv_fs_open(uv_default_loop(), &open_req, argv[1], O_RDONLY, 0, on_open); uv_run(uv_default_loop(), UV_RUN_DEFAULT); uv_fs_req_cleanup(&open_req); uv_fs_req_cleanup(&read_req); uv_fs_req_cleanup(&write_req); return 0; }NINDENT NINDENT WARNING: NDENT 0.0 NDENT 3.5 The uv_fs_req_cleanup() function must always be called on filesystem requests to free internal memory allocations in libuv. NINDENT NINDENT
int uv_fs_close(uv_loop_t* loop, uv_fs_t* req, uv_file file, uv_fs_cb cb); int uv_fs_open(uv_loop_t* loop, uv_fs_t* req, const char* path, int flags, int mode, uv_fs_cb cb); int uv_fs_read(uv_loop_t* loop, uv_fs_t* req, uv_file file, const uv_buf_t bufs[], unsigned int nbufs, int64_t offset, uv_fs_cb cb); int uv_fs_unlink(uv_loop_t* loop, uv_fs_t* req, const char* path, uv_fs_cb cb); int uv_fs_write(uv_loop_t* loop, uv_fs_t* req, uv_file file, const uv_buf_t bufs[], unsigned int nbufs, int64_t offset, uv_fs_cb cb); int uv_fs_copyfile(uv_loop_t* loop, uv_fs_t* req, const char* path, const char* new_path, int flags, uv_fs_cb cb); int uv_fs_mkdir(uv_loop_t* loop, uv_fs_t* req, const char* path, int mode, uv_fs_cb cb); int uv_fs_mkdtemp(uv_loop_t* loop, uv_fs_t* req, const char* tpl, uv_fs_cb cb); int uv_fs_rmdir(uv_loop_t* loop, uv_fs_t* req, const char* path, uv_fs_cb cb); int uv_fs_scandir(uv_loop_t* loop, uv_fs_t* req, const char* path, int flags, uv_fs_cb cb); int uv_fs_scandir_next(uv_fs_t* req, uv_dirent_t* ent); int uv_fs_opendir(uv_loop_t* loop, uv_fs_t* req, const char* path, uv_fs_cb cb); int uv_fs_readdir(uv_loop_t* loop, uv_fs_t* req, uv_dir_t* dir, uv_fs_cb cb); int uv_fs_closedir(uv_loop_t* loop, uv_fs_t* req, uv_dir_t* dir, uv_fs_cb cb); int uv_fs_stat(uv_loop_t* loop, uv_fs_t* req, const char* path, uv_fs_cb cb); int uv_fs_fstat(uv_loop_t* loop, uv_fs_t* req, uv_file file, uv_fs_cb cb); int uv_fs_rename(uv_loop_t* loop, uv_fs_t* req, const char* path, const char* new_path, uv_fs_cb cb); int uv_fs_fsync(uv_loop_t* loop, uv_fs_t* req, uv_file file, uv_fs_cb cb); int uv_fs_fdatasync(uv_loop_t* loop, uv_fs_t* req, uv_file file, uv_fs_cb cb); int uv_fs_ftruncate(uv_loop_t* loop, uv_fs_t* req, uv_file file, int64_t offset, uv_fs_cb cb); int uv_fs_sendfile(uv_loop_t* loop, uv_fs_t* req, uv_file out_fd, uv_file in_fd, int64_t in_offset, size_t length, uv_fs_cb cb); int uv_fs_access(uv_loop_t* loop, uv_fs_t* req, const char* path, int mode, uv_fs_cb cb); int uv_fs_chmod(uv_loop_t* loop, uv_fs_t* req, const char* path, int mode, uv_fs_cb cb); int uv_fs_utime(uv_loop_t* loop, uv_fs_t* req, const char* path, double atime, double mtime, uv_fs_cb cb); int uv_fs_futime(uv_loop_t* loop, uv_fs_t* req, uv_file file, double atime, double mtime, uv_fs_cb cb); int uv_fs_lstat(uv_loop_t* loop, uv_fs_t* req, const char* path, uv_fs_cb cb); int uv_fs_link(uv_loop_t* loop, uv_fs_t* req, const char* path, const char* new_path, uv_fs_cb cb); int uv_fs_symlink(uv_loop_t* loop, uv_fs_t* req, const char* path, const char* new_path, int flags, uv_fs_cb cb); int uv_fs_readlink(uv_loop_t* loop, uv_fs_t* req, const char* path, uv_fs_cb cb); int uv_fs_realpath(uv_loop_t* loop, uv_fs_t* req, const char* path, uv_fs_cb cb); int uv_fs_fchmod(uv_loop_t* loop, uv_fs_t* req, uv_file file, int mode, uv_fs_cb cb); int uv_fs_chown(uv_loop_t* loop, uv_fs_t* req, const char* path, uv_uid_t uid, uv_gid_t gid, uv_fs_cb cb); int uv_fs_fchown(uv_loop_t* loop, uv_fs_t* req, uv_file file, uv_uid_t uid, uv_gid_t gid, uv_fs_cb cb); int uv_fs_lchown(uv_loop_t* loop, uv_fs_t* req, const char* path, uv_uid_t uid, uv_gid_t gid, uv_fs_cb cb);NINDENT NINDENT
int uv_read_start(uv_stream_t*, uv_alloc_cb alloc_cb, uv_read_cb read_cb); int uv_read_stop(uv_stream_t*); int uv_write(uv_write_t* req, uv_stream_t* handle, const uv_buf_t bufs[], unsigned int nbufs, uv_write_cb cb);NINDENT NINDENT The stream based functions are simpler to use than the filesystem ones and libuv will automatically keep reading from a stream when uv_read_start() is called once, until uv_read_stop() is called. The discrete unit of data is the buffer -- uv_buf_t. This is simply a collection of a pointer to bytes (uv_buf_t.base) and the length (uv_buf_t.len). The uv_buf_t is lightweight and passed around by value. What does require management is the actual bytes, which have to be allocated and freed by the application. ERROR: NDENT 0.0 NDENT 3.5 THIS PROGRAM DOES NOT ALWAYS WORK, NEED SOMETHING BETTER** NINDENT NINDENT To demonstrate streams we will need to use uv_pipe_t. This allows streaming local files [2]. Here is a simple tee utility using libuv. Doing all operations asynchronously shows the power of evented I/O. The two writes won\(aqt block each other, but we have to be careful to copy over the buffer data to ensure we don\(aqt free a buffer until it has been written. The program is to be executed as: NDENT 0.0 NDENT 3.5
./uvtee <output_file>NINDENT NINDENT We start off opening pipes on the files we require. libuv pipes to a file are opened as bidirectional by default. uvtee/main.c - read on pipes NDENT 0.0 NDENT 3.5
int main(int argc, char **argv) { loop = uv_default_loop(); uv_pipe_init(loop, &stdin_pipe, 0); uv_pipe_open(&stdin_pipe, 0); uv_pipe_init(loop, &stdout_pipe, 0); uv_pipe_open(&stdout_pipe, 1); uv_fs_t file_req; int fd = uv_fs_open(loop, &file_req, argv[1], O_CREAT | O_RDWR, 0644, NULL); uv_pipe_init(loop, &file_pipe, 0); uv_pipe_open(&file_pipe, fd); uv_read_start((uv_stream_t*)&stdin_pipe, alloc_buffer, read_stdin); uv_run(loop, UV_RUN_DEFAULT); return 0; }NINDENT NINDENT The third argument of uv_pipe_init() should be set to 1 for IPC using named pipes. This is covered in processes. The uv_pipe_open() call associates the pipe with the file descriptor, in this case 0 (standard input). We start monitoring stdin. The alloc_buffer callback is invoked as new buffers are required to hold incoming data. read_stdin will be called with these buffers. uvtee/main.c - reading buffers NDENT 0.0 NDENT 3.5
void alloc_buffer(uv_handle_t *handle, size_t suggested_size, uv_buf_t *buf) { *buf = uv_buf_init((char*) malloc(suggested_size), suggested_size); } void read_stdin(uv_stream_t *stream, ssize_t nread, const uv_buf_t *buf) { if (nread < 0){ if (nread == UV_EOF){ // end of file uv_close((uv_handle_t *)&stdin_pipe, NULL); uv_close((uv_handle_t *)&stdout_pipe, NULL); uv_close((uv_handle_t *)&file_pipe, NULL); } } else if (nread > 0) { write_data((uv_stream_t *)&stdout_pipe, nread, *buf, on_stdout_write); write_data((uv_stream_t *)&file_pipe, nread, *buf, on_file_write); } // OK to free buffer as write_data copies it. if (buf->base) free(buf->base); }NINDENT NINDENT The standard malloc is sufficient here, but you can use any memory allocation scheme. For example, node.js uses its own slab allocator which associates buffers with V8 objects. The read callback nread parameter is less than 0 on any error. This error might be EOF, in which case we close all the streams, using the generic close function uv_close() which deals with the handle based on its internal type. Otherwise nread is a non-negative number and we can attempt to write that many bytes to the output streams. Finally remember that buffer allocation and deallocation is application responsibility, so we free the data. The allocation callback may return a buffer with length zero if it fails to allocate memory. In this case, the read callback is invoked with error UV_ENOBUFS. libuv will continue to attempt to read the stream though, so you must explicitly call uv_close() if you want to stop when allocation fails. The read callback may be called with nread = 0, indicating that at this point there is nothing to be read. Most applications will just ignore this. uvtee/main.c - Write to pipe NDENT 0.0 NDENT 3.5
typedef struct { uv_write_t req; uv_buf_t buf; } write_req_t; void free_write_req(uv_write_t *req) { write_req_t *wr = (write_req_t*) req; free(wr->buf.base); free(wr); } void on_stdout_write(uv_write_t *req, int status) { free_write_req(req); } void on_file_write(uv_write_t *req, int status) { free_write_req(req); } void write_data(uv_stream_t *dest, size_t size, uv_buf_t buf, uv_write_cb cb) { write_req_t *req = (write_req_t*) malloc(sizeof(write_req_t)); req->buf = uv_buf_init((char*) malloc(size), size); memcpy(req->buf.base, buf.base, size); uv_write((uv_write_t*) req, (uv_stream_t*)dest, &req->buf, 1, cb); }NINDENT NINDENT write_data() makes a copy of the buffer obtained from read. This buffer does not get passed through to the write callback trigged on write completion. To get around this we wrap a write request and a buffer in write_req_t and unwrap it in the callbacks. We make a copy so we can free the two buffers from the two calls to write_data independently of each other. While acceptable for a demo program like this, you\(aqll probably want smarter memory management, like reference counted buffers or a pool of buffers in any major application. WARNING: NDENT 0.0 NDENT 3.5 If your program is meant to be used with other programs it may knowingly or unknowingly be writing to a pipe. This makes it susceptible to \%aborting on receiving a SIGPIPE. It is a good idea to insert: NDENT 0.0 NDENT 3.5
signal(SIGPIPE, SIG_IGN)NINDENT NINDENT in the initialization stages of your application. NINDENT NINDENT
./onchange <command> <file1> [file2] ...NINDENT NINDENT The file change notification is started using uv_fs_event_init(): onchange/main.c - The setup NDENT 0.0 NDENT 3.5
int main(int argc, char **argv) { if (argc <= 2) { fprintf(stderr, "Usage: %s <command> <file1> [file2 ...]\en", argv[0]); return 1; } loop = uv_default_loop(); command = argv[1]; while (argc-- > 2) { fprintf(stderr, "Adding watch on %s\en", argv[argc]); uv_fs_event_t *fs_event_req = malloc(sizeof(uv_fs_event_t)); uv_fs_event_init(loop, fs_event_req); // The recursive flag watches subdirectories too. uv_fs_event_start(fs_event_req, run_command, argv[argc], UV_FS_EVENT_RECURSIVE); } return uv_run(loop, UV_RUN_DEFAULT); }NINDENT NINDENT The third argument is the actual file or directory to monitor. The last argument, flags, can be: NDENT 0.0 NDENT 3.5
/* * Flags to be passed to uv_fs_event_start(). */ enum uv_fs_event_flags { UV_FS_EVENT_WATCH_ENTRY = 1, UV_FS_EVENT_STAT = 2, UV_FS_EVENT_RECURSIVE = 4 };NINDENT NINDENT UV_FS_EVENT_WATCH_ENTRY and UV_FS_EVENT_STAT don\(aqt do anything (yet). UV_FS_EVENT_RECURSIVE will start watching subdirectories as well on supported platforms. The callback will receive the following arguments: NDENT 0.0 NDENT 3.5 NDENT 0.0
int flags - one of UV_RENAME or UV_CHANGE, or a bitwise OR of both. NINDENT
void run_command(uv_fs_event_t *handle, const char *filename, int events, int status) { char path[1024]; size_t size = 1023; // Does not handle error if path is longer than 1023. uv_fs_event_getpath(handle, path, &size); path[size] = \(aq\e0\(aq; fprintf(stderr, "Change detected in %s: ", path); if (events & UV_RENAME) fprintf(stderr, "renamed"); if (events & UV_CHANGE) fprintf(stderr, "changed"); fprintf(stderr, " %s\en", filename ? filename : ""); system(command); }NINDENT NINDENT
----
0
uv_close((uv_handle_t*) client, on_close); } } int main() { loop = uv_default_loop(); uv_tcp_t server; uv_tcp_init(loop, &server); uv_ip4_addr("0.0.0.0", DEFAULT_PORT, &addr); uv_tcp_bind(&server, (const struct sockaddr*)&addr, 0); int r = uv_listen((uv_stream_t*) &server, DEFAULT_BACKLOG, on_new_connection); if (r) { fprintf(stderr, "Listen error %s\en", uv_strerror(r)); return 1; } return uv_run(loop, UV_RUN_DEFAULT); }NINDENT NINDENT You can see the utility function uv_ip4_addr being used to convert from a human readable IP address, port pair to the sockaddr_in structure required by the BSD socket APIs. The reverse can be obtained using uv_ip4_name. NOTE: NDENT 0.0 NDENT 3.5 There are uv_ip6_* analogues for the ip4 functions. NINDENT NINDENT Most of the setup functions are synchronous since they are CPU-bound. uv_listen is where we return to libuv\(aqs callback style. The second arguments is the backlog queue -- the maximum length of queued connections. When a connection is initiated by clients, the callback is required to set up a handle for the client socket and associate the handle using uv_accept. In this case we also establish interest in reading from this stream. tcp-echo-server/main.c - Accepting the client NDENT 0.0 NDENT 3.5
free(buf->base); } void on_new_connection(uv_stream_t *server, int status) { if (status < 0) { fprintf(stderr, "New connection error %s\en", uv_strerror(status)); // error! return; } uv_tcp_t *client = (uv_tcp_t*) malloc(sizeof(uv_tcp_t)); uv_tcp_init(loop, client); if (uv_accept(server, (uv_stream_t*) client) == 0) { uv_read_start((uv_stream_t*) client, alloc_buffer, echo_read); }NINDENT NINDENT The remaining set of functions is very similar to the streams example and can be found in the code. Just remember to call uv_close when the socket isn\(aqt required. This can be done even in the uv_listen callback if you are not interested in accepting the connection.
uv_tcp_t* socket = (uv_tcp_t*)malloc(sizeof(uv_tcp_t)); uv_tcp_init(loop, socket); uv_connect_t* connect = (uv_connect_t*)malloc(sizeof(uv_connect_t)); struct sockaddr_in dest; uv_ip4_addr("127.0.0.1", 80, &dest); uv_tcp_connect(connect, socket, (const struct sockaddr*)&dest, on_connect);NINDENT NINDENT where on_connect will be called after the connection is established. The callback receives the uv_connect_t struct, which has a member .handle pointing to the socket.
uv_loop_t *loop; uv_udp_t send_socket; uv_udp_t recv_socket; int main() { loop = uv_default_loop(); uv_udp_init(loop, &recv_socket); struct sockaddr_in recv_addr; uv_ip4_addr("0.0.0.0", 68, &recv_addr); uv_udp_bind(&recv_socket, (const struct sockaddr *)&recv_addr, UV_UDP_REUSEADDR); uv_udp_recv_start(&recv_socket, alloc_buffer, on_read); uv_udp_init(loop, &send_socket); struct sockaddr_in broadcast_addr; uv_ip4_addr("0.0.0.0", 0, &broadcast_addr); uv_udp_bind(&send_socket, (const struct sockaddr *)&broadcast_addr, 0); uv_udp_set_broadcast(&send_socket, 1); uv_udp_send_t send_req; uv_buf_t discover_msg = make_discover_msg(); struct sockaddr_in send_addr; uv_ip4_addr("255.255.255.255", 67, &send_addr); uv_udp_send(&send_req, &send_socket, &discover_msg, 1, (const struct sockaddr *)&send_addr, on_send); return uv_run(loop, UV_RUN_DEFAULT); }NINDENT NINDENT NOTE: NDENT 0.0 NDENT 3.5 The IP address 0.0.0.0 is used to bind to all interfaces. The IP address 255.255.255.255 is a broadcast address meaning that packets will be sent to all interfaces on the subnet. port 0 means that the OS randomly assigns a port. NINDENT NINDENT First we setup the receiving socket to bind on all interfaces on port 68 (DHCP client) and start a read on it. This will read back responses from any DHCP server that replies. We use the UV_UDP_REUSEADDR flag to play nice with any other system DHCP clients that are running on this computer on the same port. Then we setup a similar send socket and use uv_udp_send to send a broadcast message on port 67 (DHCP server). It is necessary to set the broadcast flag, otherwise you will get an EACCES error [1]. The exact message being sent is not relevant to this book and you can study the code if you are interested. As usual the read and write callbacks will receive a status code of < 0 if something went wrong. Since UDP sockets are not connected to a particular peer, the read callback receives an extra parameter about the sender of the packet. nread may be zero if there is no more data to be read. If addr is NULL, it indicates there is nothing to read (the callback shouldn\(aqt do anything), if not NULL, it indicates that an empty datagram was received from the host at addr. The flags parameter may be UV_UDP_PARTIAL if the buffer provided by your allocator was not large enough to hold the data. In this case the OS will discard the data that could not fit (That\(aqs UDP for you!). udp-dhcp/main.c - Reading packets NDENT 0.0 NDENT 3.5
void on_read(uv_udp_t *req, ssize_t nread, const uv_buf_t *buf, const struct sockaddr *addr, unsigned flags) { if (nread < 0) { fprintf(stderr, "Read error %s\en", uv_err_name(nread)); uv_close((uv_handle_t*) req, NULL); free(buf->base); return; } char sender[17] = { 0 }; uv_ip4_name((const struct sockaddr_in*) addr, sender, 16); fprintf(stderr, "Recv from %s\en", sender); // ... DHCP specific code unsigned int *as_integer = (unsigned int*)buf->base; unsigned int ipbin = ntohl(as_integer[4]); unsigned char ip[4] = {0}; int i; for (i = 0; i < 4; i++) ip[i] = (ipbin >> i*8) & 0xff; fprintf(stderr, "Offered IP %d.%d.%d.%d\en", ip[3], ip[2], ip[1], ip[0]); free(buf->base); uv_udp_recv_stop(req); }NINDENT NINDENT
int main() { loop = uv_default_loop(); struct addrinfo hints; hints.ai_family = PF_INET; hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; hints.ai_flags = 0; uv_getaddrinfo_t resolver; fprintf(stderr, "irc.freenode.net is... "); int r = uv_getaddrinfo(loop, &resolver, on_resolved, "irc.freenode.net", "6667", &hints); if (r) { fprintf(stderr, "getaddrinfo call error %s\en", uv_err_name(r)); return 1; } return uv_run(loop, UV_RUN_DEFAULT); }NINDENT NINDENT If uv_getaddrinfo returns non-zero, something went wrong in the setup and your callback won\(aqt be invoked at all. All arguments can be freed immediately after uv_getaddrinfo returns. The hostname, servname and hints structures are documented in \%the getaddrinfo man page. The callback can be NULL in which case the function will run synchronously. In the resolver callback, you can pick any IP from the linked list of struct addrinfo(s). This also demonstrates uv_tcp_connect. It is necessary to call uv_freeaddrinfo in the callback. dns/main.c NDENT 0.0 NDENT 3.5
void on_resolved(uv_getaddrinfo_t *resolver, int status, struct addrinfo *res) { if (status < 0) { fprintf(stderr, "getaddrinfo callback error %s\en", uv_err_name(status)); return; } char addr[17] = {\(aq\e0\(aq}; uv_ip4_name((struct sockaddr_in*) res->ai_addr, addr, 16); fprintf(stderr, "%s\en", addr); uv_connect_t *connect_req = (uv_connect_t*) malloc(sizeof(uv_connect_t)); uv_tcp_t *socket = (uv_tcp_t*) malloc(sizeof(uv_tcp_t)); uv_tcp_init(loop, socket); uv_tcp_connect(connect_req, socket, (const struct sockaddr*) res->ai_addr, on_connect); uv_freeaddrinfo(res); }NINDENT NINDENT libuv also provides the inverse \%uv_getnameinfo.
#include <stdio.h> #include <uv.h> int main() { char buf[512]; uv_interface_address_t *info; int count, i; uv_interface_addresses(&info, &count); i = count; printf("Number of interfaces: %d\en", count); while (i--) { uv_interface_address_t interface = info[i]; printf("Name: %s\en", interface.name); printf("Internal? %s\en", interface.is_internal ? "Yes" : "No"); if (interface.address.address4.sin_family == AF_INET) { uv_ip4_name(&interface.address.address4, buf, sizeof(buf)); printf("IPv4 address: %s\en", buf); } else if (interface.address.address4.sin_family == AF_INET6) { uv_ip6_name(&interface.address.address6, buf, sizeof(buf)); printf("IPv6 address: %s\en", buf); } printf("\en"); } uv_free_interface_addresses(info, count); return 0; }NINDENT NINDENT is_internal is true for loopback interfaces. Note that if a physical interface has multiple IPv4/IPv6 addresses, the name will be reported multiple times, with each address being reported once.
----
0
int main() { int tracklen = 10; uv_thread_t hare_id; uv_thread_t tortoise_id; uv_thread_create(&hare_id, hare, &tracklen); uv_thread_create(&tortoise_id, tortoise, &tracklen); uv_thread_join(&hare_id); uv_thread_join(&tortoise_id); return 0; }NINDENT NINDENT TIP: NDENT 0.0 NDENT 3.5 uv_thread_t is just an alias for pthread_t on Unix, but this is an implementation detail, avoid depending on it to always be true. NINDENT NINDENT The second parameter is the function which will serve as the entry point for the thread, the last parameter is a void * argument which can be used to pass custom parameters to the thread. The function hare will now run in a separate thread, scheduled pre-emptively by the operating system: thread-create/main.c NDENT 0.0 NDENT 3.5
void hare(void *arg) { int tracklen = *((int *) arg); while (tracklen) { tracklen--; sleep(1); fprintf(stderr, "Hare ran another step\en"); } fprintf(stderr, "Hare done running!\en"); }NINDENT NINDENT Unlike pthread_join() which allows the target thread to pass back a value to the calling thread using a second parameter, uv_thread_join() does not. To send values use \%Inter-thread communication.
int uv_mutex_init(uv_mutex_t* handle); int uv_mutex_init_recursive(uv_mutex_t* handle); void uv_mutex_destroy(uv_mutex_t* handle); void uv_mutex_lock(uv_mutex_t* handle); int uv_mutex_trylock(uv_mutex_t* handle); void uv_mutex_unlock(uv_mutex_t* handle);NINDENT NINDENT The uv_mutex_init(), uv_mutex_init_recursive() and uv_mutex_trylock() functions will return 0 on success, and an error code otherwise. If libuv has been compiled with debugging enabled, uv_mutex_destroy(), uv_mutex_lock() and uv_mutex_unlock() will abort() on error. Similarly uv_mutex_trylock() will abort if the error is anything other than EAGAIN or EBUSY. Recursive mutexes are supported, but you should not rely on them. Also, they should not be used with uv_cond_t variables. The default BSD mutex implementation will raise an error if a thread which has locked a mutex attempts to lock it again. For example, a construct like: NDENT 0.0 NDENT 3.5
uv_mutex_init(a_mutex); uv_mutex_lock(a_mutex); uv_thread_create(thread_id, entry, (void *)a_mutex); uv_mutex_lock(a_mutex); // more things hereNINDENT NINDENT can be used to wait until another thread initializes some stuff and then unlocks a_mutex but will lead to your program crashing if in debug mode, or return an error in the second call to uv_mutex_lock(). NOTE: NDENT 0.0 NDENT 3.5 Mutexes on Windows are always recursive. NINDENT NINDENT
#include <stdio.h> #include <uv.h> uv_barrier_t blocker; uv_rwlock_t numlock; int shared_num; void reader(void *n) { int num = *(int *)n; int i; for (i = 0; i < 20; i++) { uv_rwlock_rdlock(&numlock); printf("Reader %d: acquired lock\en", num); printf("Reader %d: shared num = %d\en", num, shared_num); uv_rwlock_rdunlock(&numlock); printf("Reader %d: released lock\en", num); } uv_barrier_wait(&blocker); } void writer(void *n) { int num = *(int *)n; int i; for (i = 0; i < 20; i++) { uv_rwlock_wrlock(&numlock); printf("Writer %d: acquired lock\en", num); shared_num++; printf("Writer %d: incremented shared num = %d\en", num, shared_num); uv_rwlock_wrunlock(&numlock); printf("Writer %d: released lock\en", num); } uv_barrier_wait(&blocker); } int main() { uv_barrier_init(&blocker, 4); shared_num = 0; uv_rwlock_init(&numlock); uv_thread_t threads[3]; int thread_nums[] = {1, 2, 1}; uv_thread_create(&threads[0], reader, &thread_nums[0]); uv_thread_create(&threads[1], reader, &thread_nums[1]); uv_thread_create(&threads[2], writer, &thread_nums[2]); uv_barrier_wait(&blocker); uv_barrier_destroy(&blocker); uv_rwlock_destroy(&numlock); return 0; }NINDENT NINDENT Run this and observe how the readers will sometimes overlap. In case of multiple writers, schedulers will usually give them higher priority, so if you add two writers, you\(aqll see that both writers tend to finish first before the readers get a chance again. We also use barriers in the above example so that the main thread can wait for all readers and writers to indicate they have ended.
/* Initialize guard */ static uv_once_t once_only = UV_ONCE_INIT; int i = 0; void increment() { i++; } void thread1() { /* ... work */ uv_once(once_only, increment); } void thread2() { /* ... work */ uv_once(once_only, increment); } int main() { /* ... spawn threads */ }NINDENT NINDENT After all threads are done, i == 1. libuv v0.11.11 onwards also added a uv_key_t struct and \%api for thread-local storage.
void fib(uv_work_t *req) { int n = *(int *) req->data; if (random() % 2) sleep(1); else sleep(3); long fib = fib_(n); fprintf(stderr, "%dth fibonacci is %lu\en", n, fib); } void after_fib(uv_work_t *req, int status) { fprintf(stderr, "Done calculating %dth fibonacci\en", *(int *) req->data); }NINDENT NINDENT The actual task function is simple, nothing to show that it is going to be run in a separate thread. The uv_work_t structure is the clue. You can pass arbitrary data through it using the void* data field and use it to communicate to and from the thread. But be sure you are using proper locks if you are changing things while both threads may be running. The trigger is uv_queue_work: queue-work/main.c NDENT 0.0 NDENT 3.5
int main() { loop = uv_default_loop(); int data[FIB_UNTIL]; uv_work_t req[FIB_UNTIL]; int i; for (i = 0; i < FIB_UNTIL; i++) { data[i] = i; req[i].data = (void *) &data[i]; uv_queue_work(loop, &req[i], fib, after_fib); } return uv_run(loop, UV_RUN_DEFAULT); }NINDENT NINDENT The thread function will be launched in a separate thread, passed the uv_work_t structure and once the function returns, the after function will be called on the thread the event loop is running in. It will be passed the same structure. For writing wrappers to blocking libraries, a common pattern is to use a baton to exchange data. Since libuv version 0.9.4 an additional function, uv_cancel(), is available. This allows you to cancel tasks on the libuv work queue. Only tasks that are yet to be started can be cancelled. If a task has already started executing, or it has finished executing, uv_cancel() will fail. uv_cancel() is useful to cleanup pending tasks if the user requests termination. For example, a music player may queue up multiple directories to be scanned for audio files. If the user terminates the program, it should quit quickly and not wait until all pending requests are run. Let\(aqs modify the fibonacci example to demonstrate uv_cancel(). We first set up a signal handler for termination. queue-cancel/main.c NDENT 0.0 NDENT 3.5
int main() { loop = uv_default_loop(); int data[FIB_UNTIL]; int i; for (i = 0; i < FIB_UNTIL; i++) { data[i] = i; fib_reqs[i].data = (void *) &data[i]; uv_queue_work(loop, &fib_reqs[i], fib, after_fib); } uv_signal_t sig; uv_signal_init(loop, &sig); uv_signal_start(&sig, signal_handler, SIGINT); return uv_run(loop, UV_RUN_DEFAULT); }NINDENT NINDENT When the user triggers the signal by pressing Ctrl+C we send uv_cancel() to all the workers. uv_cancel() will return 0 for those that are already executing or finished. queue-cancel/main.c NDENT 0.0 NDENT 3.5
void signal_handler(uv_signal_t *req, int signum) { printf("Signal received!\en"); int i; for (i = 0; i < FIB_UNTIL; i++) { uv_cancel((uv_req_t*) &fib_reqs[i]); } uv_signal_stop(req); }NINDENT NINDENT For tasks that do get cancelled successfully, the after function is called with status set to UV_ECANCELED. queue-cancel/main.c NDENT 0.0 NDENT 3.5
void after_fib(uv_work_t *req, int status) { if (status == UV_ECANCELED) fprintf(stderr, "Calculation of %d cancelled.\en", *(int *) req->data); }NINDENT NINDENT uv_cancel() can also be used with uv_fs_t and uv_getaddrinfo_t requests. For the filesystem family of functions, uv_fs_t.errorno will be set to UV_ECANCELED. TIP: NDENT 0.0 NDENT 3.5 A well designed program would have a way to terminate long running workers that have already started executing. Such a worker could periodically check for a variable that only the main process sets to signal termination. NINDENT NINDENT
uv_loop_t *loop; uv_async_t async; int main() { loop = uv_default_loop(); uv_work_t req; int size = 10240; req.data = (void*) &size; uv_async_init(loop, &async, print_progress); uv_queue_work(loop, &req, fake_download, after); return uv_run(loop, UV_RUN_DEFAULT); }NINDENT NINDENT The async thread communication works on loops so although any thread can be the message sender, only threads with libuv loops can be receivers (or rather the loop is the receiver). libuv will invoke the callback (print_progress) with the async watcher whenever it receives a message. WARNING: NDENT 0.0 NDENT 3.5 It is important to realize that since the message send is async, the callback may be invoked immediately after uv_async_send is called in another thread, or it may be invoked after some time. libuv may also combine multiple calls to uv_async_send and invoke your callback only once. The only guarantee that libuv makes is -- The callback function is called at least once after the call to uv_async_send. If you have no pending calls to uv_async_send, the callback won\(aqt be called. If you make two or more calls, and libuv hasn\(aqt had a chance to run the callback yet, it may invoke your callback only once for the multiple invocations of uv_async_send. Your callback will never be called twice for just one event. NINDENT NINDENT progress/main.c NDENT 0.0 NDENT 3.5
double percentage; void fake_download(uv_work_t *req) { int size = *((int*) req->data); int downloaded = 0; while (downloaded < size) { percentage = downloaded*100.0/size; async.data = (void*) &percentage; uv_async_send(&async); sleep(1); downloaded += (200+random())%1000; // can only download max 1000bytes/sec, // but at least a 200; } }NINDENT NINDENT In the download function, we modify the progress indicator and queue the message for delivery with uv_async_send. Remember: uv_async_send is also non-blocking and will return immediately. progress/main.c NDENT 0.0 NDENT 3.5
void print_progress(uv_async_t *handle) { double percentage = *((double*) handle->data); fprintf(stderr, "Downloaded %.2f%%\en", percentage); }NINDENT NINDENT The callback is a standard libuv pattern, extracting the data from the watcher. Finally it is important to remember to clean up the watcher. progress/main.c NDENT 0.0 NDENT 3.5
void after(uv_work_t *req, int status) { fprintf(stderr, "Download complete\en"); uv_close((uv_handle_t*) &async, NULL); }NINDENT NINDENT After this example, which showed the abuse of the data field, \%bnoordhuis pointed out that using the data field is not thread safe, and uv_async_send() is actually only meant to wake up the event loop. Use a mutex or rwlock to ensure accesses are performed in the right order. NOTE: NDENT 0.0 NDENT 3.5 mutexes and rwlocks DO NOT work inside a signal handler, whereas uv_async_send does. NINDENT NINDENT One use case where uv_async_send is required is when interoperating with libraries that require thread affinity for their functionality. For example in node.js, a v8 engine instance, contexts and its objects are bound to the thread that the v8 instance was started in. Interacting with v8 data structures from another thread can lead to undefined results. Now consider some node.js module which binds a third party library. It may go something like this: NDENT 0.0
var lib = require(\(aqlib\(aq); lib.on_progress(function() { console.log("Progress"); }); lib.do(); // do other stuffNINDENT NINDENT
----
0
uv_loop_t *loop; uv_process_t child_req; uv_process_options_t options; int main() { loop = uv_default_loop(); char* args[3]; args[0] = "mkdir"; args[1] = "test-dir"; args[2] = NULL; options.exit_cb = on_exit; options.file = "mkdir"; options.args = args; int r; if ((r = uv_spawn(loop, &child_req, &options))) { fprintf(stderr, "%s\en", uv_strerror(r)); return 1; } else { fprintf(stderr, "Launched process with ID %d\en", child_req.pid); } return uv_run(loop, UV_RUN_DEFAULT); }NINDENT NINDENT NOTE: NDENT 0.0 NDENT 3.5 options is implicitly initialized with zeros since it is a global variable. If you change options to a local variable, remember to initialize it to null out all unused fields: NDENT 0.0 NDENT 3.5
uv_process_options_t options = {0};NINDENT NINDENT NINDENT NINDENT The uv_process_t struct only acts as the handle, all options are set via uv_process_options_t. To simply launch a process, you need to set only the file and args fields. file is the program to execute. Since uv_spawn uses \%execvp(3) internally, there is no need to supply the full path. Finally as per underlying conventions, the arguments array has to be one larger than the number of arguments, with the last element being NULL. After the call to uv_spawn, uv_process_t.pid will contain the process ID of the child process. The exit callback will be invoked with the exit status and the type of signal which caused the exit. spawn/main.c NDENT 0.0 NDENT 3.5
void on_exit(uv_process_t *req, int64_t exit_status, int term_signal) { fprintf(stderr, "Process exited with status %" PRId64 ", signal %d\en", exit_status, term_signal); uv_close((uv_handle_t*) req, NULL);NINDENT NINDENT It is required to close the process watcher after the process exits.
int main() { loop = uv_default_loop(); char* args[3]; args[0] = "sleep"; args[1] = "100"; args[2] = NULL; options.exit_cb = NULL; options.file = "sleep"; options.args = args; options.flags = UV_PROCESS_DETACHED; int r; if ((r = uv_spawn(loop, &child_req, &options))) { fprintf(stderr, "%s\en", uv_strerror(r)); return 1; } fprintf(stderr, "Launched sleep with PID %d\en", child_req.pid); uv_unref((uv_handle_t*) &child_req); return uv_run(loop, UV_RUN_DEFAULT);NINDENT NINDENT Just remember that the handle is still monitoring the child, so your program won\(aqt exit. Use uv_unref() if you want to be more fire-and-forget.
uv_err_t uv_kill(int pid, int signum);NINDENT NINDENT For processes started using libuv, you may use uv_process_kill instead, which accepts the uv_process_t watcher as the first argument, rather than the pid. In this case, remember to call uv_close on the watcher.
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <uv.h> uv_loop_t* create_loop() { uv_loop_t *loop = malloc(sizeof(uv_loop_t)); if (loop) { uv_loop_init(loop); } return loop; } void signal_handler(uv_signal_t *handle, int signum) { printf("Signal received: %d\en", signum); uv_signal_stop(handle); } // two signal handlers in one loop void thread1_worker(void *userp) { uv_loop_t *loop1 = create_loop(); uv_signal_t sig1a, sig1b; uv_signal_init(loop1, &sig1a); uv_signal_start(&sig1a, signal_handler, SIGUSR1); uv_signal_init(loop1, &sig1b); uv_signal_start(&sig1b, signal_handler, SIGUSR1); uv_run(loop1, UV_RUN_DEFAULT); } // two signal handlers, each in its own loop void thread2_worker(void *userp) { uv_loop_t *loop2 = create_loop(); uv_loop_t *loop3 = create_loop(); uv_signal_t sig2; uv_signal_init(loop2, &sig2); uv_signal_start(&sig2, signal_handler, SIGUSR1); uv_signal_t sig3; uv_signal_init(loop3, &sig3); uv_signal_start(&sig3, signal_handler, SIGUSR1); while (uv_run(loop2, UV_RUN_NOWAIT) || uv_run(loop3, UV_RUN_NOWAIT)) { } } int main() { printf("PID %d\en", getpid()); uv_thread_t thread1, thread2; uv_thread_create(&thread1, thread1_worker, 0); uv_thread_create(&thread2, thread2_worker, 0); uv_thread_join(&thread1); uv_thread_join(&thread2); return 0; }NINDENT NINDENT NOTE: NDENT 0.0 NDENT 3.5 uv_run(loop, UV_RUN_NOWAIT) is similar to uv_run(loop, UV_RUN_ONCE) in that it will process only one event. UV_RUN_ONCE blocks if there are no pending events, while UV_RUN_NOWAIT will return immediately. We use NOWAIT so that one of the loops isn\(aqt starved because the other one has no pending activity. NINDENT NINDENT Send SIGUSR1 to the process, and you\(aqll find the handler being invoked 4 times, one for each uv_signal_t. The handler just stops each handle, so that the program exits. This sort of dispatch to all handlers is very useful. A server using multiple event loops could ensure that all data was safely saved before termination, simply by every loop adding a watcher for SIGINT.
#include <stdio.h> int main() { fprintf(stderr, "This is stderr\en"); printf("This is stdout\en"); return 0; }NINDENT NINDENT The actual program proc-streams runs this while sharing only stderr. The file descriptors of the child process are set using the stdio field in uv_process_options_t. First set the stdio_count field to the number of file descriptors being set. uv_process_options_t.stdio is an array of uv_stdio_container_t, which is: NDENT 0.0 NDENT 3.5
typedef struct uv_stdio_container_s { uv_stdio_flags flags; union { uv_stream_t* stream; int fd; } data; } uv_stdio_container_t;NINDENT NINDENT where flags can have several values. Use UV_IGNORE if it isn\(aqt going to be used. If the first three stdio fields are marked as UV_IGNORE they\(aqll redirect to /dev/null. Since we want to pass on an existing descriptor, we\(aqll use UV_INHERIT_FD. Then we set the fd to stderr. proc-streams/main.c NDENT 0.0 NDENT 3.5
int main() { loop = uv_default_loop(); /* ... */ options.stdio_count = 3; uv_stdio_container_t child_stdio[3]; child_stdio[0].flags = UV_IGNORE; child_stdio[1].flags = UV_IGNORE; child_stdio[2].flags = UV_INHERIT_FD; child_stdio[2].data.fd = 2; options.stdio = child_stdio; options.exit_cb = on_exit; options.file = args[0]; options.args = args; int r; if ((r = uv_spawn(loop, &child_req, &options))) { fprintf(stderr, "%s\en", uv_strerror(r)); return 1; } return uv_run(loop, UV_RUN_DEFAULT); }NINDENT NINDENT If you run proc-stream you\(aqll see that only the line "This is stderr" will be displayed. Try marking stdout as being inherited and see the output. It is dead simple to apply this redirection to streams. By setting flags to UV_INHERIT_STREAM and setting data.stream to the stream in the parent process, the child process can treat that stream as standard I/O. This can be used to implement something like \%CGI. A sample CGI script/executable is: cgi/tick.c NDENT 0.0 NDENT 3.5
#include <stdio.h> #include <unistd.h> int main() { int i; for (i = 0; i < 10; i++) { printf("tick\en"); fflush(stdout); sleep(1); } printf("BOOM!\en"); return 0; }NINDENT NINDENT The CGI server combines the concepts from this chapter and networking so that every client is sent ten ticks after which that connection is closed. cgi/main.c NDENT 0.0 NDENT 3.5
void on_new_connection(uv_stream_t *server, int status) { if (status == -1) { // error! return; } uv_tcp_t *client = (uv_tcp_t*) malloc(sizeof(uv_tcp_t)); uv_tcp_init(loop, client); if (uv_accept(server, (uv_stream_t*) client) == 0) { invoke_cgi_script(client); } else { uv_close((uv_handle_t*) client, NULL); }NINDENT NINDENT Here we simply accept the TCP connection and pass on the socket (stream) to invoke_cgi_script. cgi/main.c NDENT 0.0 NDENT 3.5
args[1] = NULL; /* ... finding the executable path and setting up arguments ... */ options.stdio_count = 3; uv_stdio_container_t child_stdio[3]; child_stdio[0].flags = UV_IGNORE; child_stdio[1].flags = UV_INHERIT_STREAM; child_stdio[1].data.stream = (uv_stream_t*) client; child_stdio[2].flags = UV_IGNORE; options.stdio = child_stdio; options.exit_cb = cleanup_handles; options.file = args[0]; options.args = args; // Set this so we can close the socket after the child process exits. child_req.data = (void*) client; int r; if ((r = uv_spawn(loop, &child_req, &options))) { fprintf(stderr, "%s\en", uv_strerror(r));NINDENT NINDENT The stdout of the CGI script is set to the socket so that whatever our tick script prints, gets sent to the client. By using processes, we can offload the read/write buffering to the operating system, so in terms of convenience this is great. Just be warned that creating processes is a costly task.
void remove_sock(int sig) { uv_fs_t req; uv_fs_unlink(loop, &req, PIPENAME, NULL); exit(0); } int main() { loop = uv_default_loop(); uv_pipe_t server; uv_pipe_init(loop, &server, 0); signal(SIGINT, remove_sock); int r; if ((r = uv_pipe_bind(&server, PIPENAME))) { fprintf(stderr, "Bind error %s\en", uv_err_name(r)); return 1; } if ((r = uv_listen((uv_stream_t*) &server, 128, on_new_connection))) { fprintf(stderr, "Listen error %s\en", uv_err_name(r)); return 2; } return uv_run(loop, UV_RUN_DEFAULT); }NINDENT NINDENT We name the socket echo.sock which means it will be created in the local directory. This socket now behaves no different from TCP sockets as far as the stream API is concerned. You can test this server using \%socat: NDENT 0.0 NDENT 3.5
$ socat - /path/to/socketNINDENT NINDENT A client which wants to connect to a domain socket will use: NDENT 0.0 NDENT 3.5
void uv_pipe_connect(uv_connect_t *req, uv_pipe_t *handle, const char *name, uv_connect_cb cb);NINDENT NINDENT where name will be echo.sock or similar. On Unix systems, name must point to a valid file (e.g. /tmp/echo.sock). On Windows, name follows a \e\e?\epipe\eecho.sock format.
uv_loop_t *loop; uv_pipe_t queue; int main() { loop = uv_default_loop(); uv_pipe_init(loop, &queue, 1 /* ipc */); uv_pipe_open(&queue, 0); uv_read_start((uv_stream_t*)&queue, alloc_buffer, on_new_connection); return uv_run(loop, UV_RUN_DEFAULT); }NINDENT NINDENT queue is the pipe connected to the master process on the other end, along which new file descriptors get sent. It is important to set the ipc argument of uv_pipe_init to 1 to indicate this pipe will be used for inter-process communication! Since the master will write the file handle to the standard input of the worker, we connect the pipe to stdin using uv_pipe_open. multi-echo-server/worker.c NDENT 0.0 NDENT 3.5
void on_new_connection(uv_stream_t *q, ssize_t nread, const uv_buf_t *buf) { if (nread < 0) { if (nread != UV_EOF) fprintf(stderr, "Read error %s\en", uv_err_name(nread)); uv_close((uv_handle_t*) q, NULL); return; } uv_pipe_t *pipe = (uv_pipe_t*) q; if (!uv_pipe_pending_count(pipe)) { fprintf(stderr, "No pending count\en"); return; } uv_handle_type pending = uv_pipe_pending_type(pipe); assert(pending == UV_TCP); uv_tcp_t *client = (uv_tcp_t*) malloc(sizeof(uv_tcp_t)); uv_tcp_init(loop, client); if (uv_accept(q, (uv_stream_t*) client) == 0) { uv_os_fd_t fd; uv_fileno((const uv_handle_t*) client, &fd); fprintf(stderr, "Worker %d: Accepted fd %d\en", getpid(), fd); uv_read_start((uv_stream_t*) client, alloc_buffer, echo_read); } else { uv_close((uv_handle_t*) client, NULL); } }NINDENT NINDENT First we call uv_pipe_pending_count() to ensure that a handle is available to read out. If your program could deal with different types of handles, uv_pipe_pending_type() can be used to determine the type. Although accept seems odd in this code, it actually makes sense. What accept traditionally does is get a file descriptor (the client) from another file descriptor (The listening socket). Which is exactly what we do here. Fetch the file descriptor (client) from queue. From this point the worker does standard echo server stuff. Turning now to the master, let\(aqs take a look at how the workers are launched to allow load balancing. multi-echo-server/main.c NDENT 0.0 NDENT 3.5
struct child_worker { uv_process_t req; uv_process_options_t options; uv_pipe_t pipe; } *workers;NINDENT NINDENT The child_worker structure wraps the process, and the pipe between the master and the individual process. multi-echo-server/main.c NDENT 0.0 NDENT 3.5
void setup_workers() { round_robin_counter = 0; // ... // launch same number of workers as number of CPUs uv_cpu_info_t *info; int cpu_count; uv_cpu_info(&info, &cpu_count); uv_free_cpu_info(info, cpu_count); child_worker_count = cpu_count; workers = calloc(cpu_count, sizeof(struct child_worker)); while (cpu_count--) { struct child_worker *worker = &workers[cpu_count]; uv_pipe_init(loop, &worker->pipe, 1); uv_stdio_container_t child_stdio[3]; child_stdio[0].flags = UV_CREATE_PIPE | UV_READABLE_PIPE; child_stdio[0].data.stream = (uv_stream_t*) &worker->pipe; child_stdio[1].flags = UV_IGNORE; child_stdio[2].flags = UV_INHERIT_FD; child_stdio[2].data.fd = 2; worker->options.stdio = child_stdio; worker->options.stdio_count = 3; worker->options.exit_cb = close_process_handle; worker->options.file = args[0]; worker->options.args = args; uv_spawn(loop, &worker->req, &worker->options); fprintf(stderr, "Started worker %d\en", worker->req.pid); } }NINDENT NINDENT In setting up the workers, we use the nifty libuv function uv_cpu_info to get the number of CPUs so we can launch an equal number of workers. Again it is important to initialize the pipe acting as the IPC channel with the third argument as 1. We then indicate that the child process\(aq stdin is to be a readable pipe (from the point of view of the child). Everything is straightforward till here. The workers are launched and waiting for file descriptors to be written to their standard input. It is in on_new_connection (the TCP infrastructure is initialized in main()), that we accept the client socket and pass it along to the next worker in the round-robin. multi-echo-server/main.c NDENT 0.0 NDENT 3.5
void on_new_connection(uv_stream_t *server, int status) { if (status == -1) { // error! return; } uv_tcp_t *client = (uv_tcp_t*) malloc(sizeof(uv_tcp_t)); uv_tcp_init(loop, client); if (uv_accept(server, (uv_stream_t*) client) == 0) { uv_write_t *write_req = (uv_write_t*) malloc(sizeof(uv_write_t)); dummy_buf = uv_buf_init("a", 1); struct child_worker *worker = &workers[round_robin_counter]; uv_write2(write_req, (uv_stream_t*) &worker->pipe, &dummy_buf, 1, (uv_stream_t*) client, NULL); round_robin_counter = (round_robin_counter + 1) % child_worker_count; } else { uv_close((uv_handle_t*) client, NULL); } }NINDENT NINDENT The uv_write2 call handles all the abstraction and it is simply a matter of passing in the handle (client) as the right argument. With this our multi-process echo server is operational. Thanks to Kyle for \%pointing out that uv_write2() requires a non-empty buffer even when sending handles.
----
0
static void uv__run_closing_handles(uv_loop_t* loop) { uv_handle_t* p; uv_handle_t* q; p = loop->closing_handles; loop->closing_handles = NULL; while (p) { q = p->next_closing; uv__finish_close(p); p = q; } } int uv_is_closing(const uv_handle_t* handle) { return uv__is_closing(handle); } int uv_backend_fd(const uv_loop_t* loop) {NINDENT NINDENT stop_flag is set by uv_stop(). Now all libuv callbacks are invoked within the event loop, which is why invoking uv_stop() in them will still lead to this iteration of the loop occurring. First libuv updates timers, then runs pending timer, idle and prepare callbacks, and invokes any pending I/O callbacks. If you were to call uv_stop() in any of them, stop_flag would be set. This causes uv_backend_timeout() to return 0, which is why the loop does not block on I/O. If on the other hand, you called uv_stop() in one of the check handlers, I/O has already finished and is not affected. uv_stop() is useful to shutdown a loop when a result has been computed or there is an error, without having to ensure that all handlers are stopped one by one. Here is a simple example that stops the loop and demonstrates how the current iteration of the loop still takes places. uvstop/main.c NDENT 0.0 NDENT 3.5
#include <stdio.h> #include <uv.h> int64_t counter = 0; void idle_cb(uv_idle_t *handle) { printf("Idle callback\en"); counter++; if (counter >= 5) { uv_stop(uv_default_loop()); printf("uv_stop() called\en"); } } void prep_cb(uv_prepare_t *handle) { printf("Prep callback\en"); } int main() { uv_idle_t idler; uv_prepare_t prep; uv_idle_init(uv_default_loop(), &idler); uv_idle_start(&idler, idle_cb); uv_prepare_init(uv_default_loop(), &prep); uv_prepare_start(&prep, prep_cb); uv_run(uv_default_loop(), UV_RUN_DEFAULT); return 0; }NINDENT NINDENT
uv_timer_t timer_req; uv_timer_init(loop, &timer_req); uv_timer_start(&timer_req, callback, 5000, 2000);NINDENT NINDENT will start a repeating timer, which first starts 5 seconds (the timeout) after the execution of uv_timer_start, then repeats every 2 seconds (the repeat). Use: NDENT 0.0 NDENT 3.5
uv_timer_stop(&timer_req);NINDENT NINDENT to stop the timer. This can be used safely from within the callback as well. The repeat interval can be modified at any time with: NDENT 0.0 NDENT 3.5
uv_timer_set_repeat(uv_timer_t *timer, int64_t repeat);NINDENT NINDENT which will take effect when possible. If this function is called from a timer callback, it means: NDENT 0.0
int uv_timer_again(uv_timer_t *)NINDENT NINDENT applies only to repeating timers and is equivalent to stopping the timer and then starting it with both initial timeout and repeat set to the old repeat value. If the timer hasn\(aqt been started it fails (error code UV_EINVAL) and returns -1. An actual timer example is in the \%reference count section.
void uv_ref(uv_handle_t*); void uv_unref(uv_handle_t*);NINDENT NINDENT These functions can be used to allow a loop to exit even when a watcher is active or to use custom objects to keep the loop alive. The latter can be used with interval timers. You might have a garbage collector which runs every X seconds, or your network service might send a heartbeat to others periodically, but you don\(aqt want to have to stop them along all clean exit paths or error scenarios. Or you want the program to exit when all your other watchers are done. In that case just unref the timer immediately after creation so that if it is the only watcher running then uv_run will still exit. This is also used in node.js where some libuv methods are being bubbled up to the JS API. A uv_handle_t (the superclass of all watchers) is created per JS object and can be ref/unrefed. ref-timer/main.c NDENT 0.0 NDENT 3.5
uv_loop_t *loop; uv_timer_t gc_req; uv_timer_t fake_job_req; int main() { loop = uv_default_loop(); uv_timer_init(loop, &gc_req); uv_unref((uv_handle_t*) &gc_req); uv_timer_start(&gc_req, gc, 0, 2000); // could actually be a TCP download or something uv_timer_init(loop, &fake_job_req); uv_timer_start(&fake_job_req, fake_job, 9000, 0); return uv_run(loop, UV_RUN_DEFAULT); }NINDENT NINDENT We initialize the garbage collector timer, then immediately unref it. Observe how after 9 seconds, when the fake job is done, the program automatically exits, even though the garbage collector is still running.
uv_loop_t *loop; uv_fs_t stdin_watcher; uv_idle_t idler; char buffer[1024]; int main() { loop = uv_default_loop(); uv_idle_init(loop, &idler); uv_buf_t buf = uv_buf_init(buffer, 1024); uv_fs_read(loop, &stdin_watcher, 0, &buf, 1, -1, on_type); uv_idle_start(&idler, crunch_away); return uv_run(loop, UV_RUN_DEFAULT); }NINDENT NINDENT Here we initialize the idle watcher and queue it up along with the actual events we are interested in. crunch_away will now be called repeatedly until the user types something and presses Return. Then it will be interrupted for a brief amount as the loop deals with the input data, after which it will keep calling the idle callback again. idle-compute/main.c NDENT 0.0 NDENT 3.5
void crunch_away(uv_idle_t* handle) { // Compute extra-terrestrial life // fold proteins // computer another digit of PI // or similar fprintf(stderr, "Computing PI...\en"); // just to avoid overwhelming your terminal emulator uv_idle_stop(handle); }NINDENT NINDENT
struct ftp_baton { uv_work_t req; char *host; int port; char *username; char *password; }NINDENT NINDENT NDENT 0.0 NDENT 3.5
ftp_baton *baton = (ftp_baton*) malloc(sizeof(ftp_baton)); baton->req.data = (void*) baton; baton->host = strdup("my.webhost.com"); baton->port = 21; // ... uv_queue_work(loop, &baton->req, ftp_session, ftp_cleanup);NINDENT NINDENT Here we create the baton and queue the task. Now the task function can extract the data it needs: NDENT 0.0 NDENT 3.5
void ftp_session(uv_work_t *req) { ftp_baton *baton = (ftp_baton*) req->data; fprintf(stderr, "Connecting to %s\en", baton->host); } void ftp_cleanup(uv_work_t *req) { ftp_baton *baton = (ftp_baton*) req->data; free(baton->host); // ... free(baton); }NINDENT NINDENT We then free the baton which also frees the watcher.
#include <assert.h> #include <stdio.h> #include <stdlib.h> #include <uv.h> #include <curl/curl.h> uv_loop_t *loop; CURLM *curl_handle; uv_timer_t timeout; } int main(int argc, char **argv) { loop = uv_default_loop(); if (argc <= 1) return 0; if (curl_global_init(CURL_GLOBAL_ALL)) { fprintf(stderr, "Could not init cURL\en"); return 1; } uv_timer_init(loop, &timeout); curl_handle = curl_multi_init(); curl_multi_setopt(curl_handle, CURLMOPT_SOCKETFUNCTION, handle_socket); curl_multi_setopt(curl_handle, CURLMOPT_TIMERFUNCTION, start_timeout); while (argc-- > 1) { add_download(argv[argc], argc); } uv_run(loop, UV_RUN_DEFAULT); curl_multi_cleanup(curl_handle); return 0; }NINDENT NINDENT The way each library is integrated with libuv will vary. In the case of libcurl, we can register two callbacks. The socket callback handle_socket is invoked whenever the state of a socket changes and we have to start polling it. start_timeout is called by libcurl to notify us of the next timeout interval, after which we should drive libcurl forward regardless of I/O status. This is so that libcurl can handle errors or do whatever else is required to get the download moving. Our downloader is to be invoked as: NDENT 0.0 NDENT 3.5
$ ./uvwget [url1] [url2] ...NINDENT NINDENT So we add each argument as an URL uvwget/main.c - Adding urls NDENT 0.0 NDENT 3.5
void add_download(const char *url, int num) { char filename[50]; sprintf(filename, "%d.download", num); FILE *file; file = fopen(filename, "w"); if (file == NULL) { fprintf(stderr, "Error opening %s\en", filename); return; } CURL *handle = curl_easy_init(); curl_easy_setopt(handle, CURLOPT_WRITEDATA, file); curl_easy_setopt(handle, CURLOPT_URL, url); curl_multi_add_handle(curl_handle, handle); fprintf(stderr, "Added download %s -> %s\en", url, filename); }NINDENT NINDENT We let libcurl directly write the data to a file, but much more is possible if you so desire. start_timeout will be called immediately the first time by libcurl, so things are set in motion. This simply starts a libuv \%timer which drives curl_multi_socket_action with CURL_SOCKET_TIMEOUT whenever it times out. curl_multi_socket_action is what drives libcurl, and what we call whenever sockets change state. But before we go into that, we need to poll on sockets whenever handle_socket is called. uvwget/main.c - Setting up polling NDENT 0.0 NDENT 3.5
void start_timeout(CURLM *multi, long timeout_ms, void *userp) { if (timeout_ms <= 0) timeout_ms = 1; /* 0 means directly call socket_action, but we\(aqll do it in a bit */ uv_timer_start(&timeout, on_timeout, timeout_ms, 0); } int handle_socket(CURL *easy, curl_socket_t s, int action, void *userp, void *socketp) { curl_context_t *curl_context; if (action == CURL_POLL_IN || action == CURL_POLL_OUT) { if (socketp) { curl_context = (curl_context_t*) socketp; } else { curl_context = create_curl_context(s); curl_multi_assign(curl_handle, s, (void *) curl_context); } } switch (action) { case CURL_POLL_IN: uv_poll_start(&curl_context->poll_handle, UV_READABLE, curl_perform); break; case CURL_POLL_OUT: uv_poll_start(&curl_context->poll_handle, UV_WRITABLE, curl_perform); break; case CURL_POLL_REMOVE: if (socketp) { uv_poll_stop(&((curl_context_t*)socketp)->poll_handle); destroy_curl_context((curl_context_t*) socketp); curl_multi_assign(curl_handle, s, NULL); } break; default: abort(); } return 0; }NINDENT NINDENT We are interested in the socket fd s, and the action. For every socket we create a uv_poll_t handle if it doesn\(aqt exist, and associate it with the socket using curl_multi_assign. This way socketp points to it whenever the callback is invoked. In the case that the download is done or fails, libcurl requests removal of the poll. So we stop and free the poll handle. Depending on what events libcurl wishes to watch for, we start polling with UV_READABLE or UV_WRITABLE. Now libuv will invoke the poll callback whenever the socket is ready for reading or writing. Calling uv_poll_start multiple times on the same handle is acceptable, it will just update the events mask with the new value. curl_perform is the crux of this program. uvwget/main.c - Driving libcurl. NDENT 0.0 NDENT 3.5
void curl_perform(uv_poll_t *req, int status, int events) { uv_timer_stop(&timeout); int running_handles; int flags = 0; if (status < 0) flags = CURL_CSELECT_ERR; if (!status && events & UV_READABLE) flags |= CURL_CSELECT_IN; if (!status && events & UV_WRITABLE) flags |= CURL_CSELECT_OUT; curl_context_t *context; context = (curl_context_t*)req; curl_multi_socket_action(curl_handle, context->sockfd, flags, &running_handles); check_multi_info(); }NINDENT NINDENT The first thing we do is to stop the timer, since there has been some progress in the interval. Then depending on what event triggered the callback, we set the correct flags. Then we call curl_multi_socket_action with the socket that progressed and the flags informing about what events happened. At this point libcurl does all of its internal tasks in small increments, and will attempt to return as fast as possible, which is exactly what an evented program wants in its main thread. libcurl keeps queueing messages into its own queue about transfer progress. In our case we are only interested in transfers that are completed. So we extract these messages, and clean up handles whose transfers are done. uvwget/main.c - Reading transfer status. NDENT 0.0 NDENT 3.5
void check_multi_info(void) { char *done_url; CURLMsg *message; int pending; while ((message = curl_multi_info_read(curl_handle, &pending))) { switch (message->msg) { case CURLMSG_DONE: curl_easy_getinfo(message->easy_handle, CURLINFO_EFFECTIVE_URL, &done_url); printf("%s DONE\en", done_url); curl_multi_remove_handle(curl_handle, message->easy_handle); curl_easy_cleanup(message->easy_handle); break; default: fprintf(stderr, "CURLMSG default\en"); abort(); } } }NINDENT NINDENT
#ifndef UVBOOK_PLUGIN_SYSTEM #define UVBOOK_PLUGIN_SYSTEM // Plugin authors should use this to register their plugins with mfp. void mfp_register(const char *name); #endifNINDENT NINDENT You can similarly add more functions that plugin authors can use to do useful things in your application [2]. A sample plugin using this API is: plugin/hello.c NDENT 0.0 NDENT 3.5
#include "plugin.h" void initialize() { mfp_register("Hello World!"); }NINDENT NINDENT Our interface defines that all plugins should have an initialize function which will be called by the application. This plugin is compiled as a shared library and can be loaded by running our application: NDENT 0.0 NDENT 3.5
$ ./plugin libhello.dylib Loading libhello.dylib Registered plugin "Hello World!"NINDENT NINDENT NOTE: NDENT 0.0 NDENT 3.5 The shared library filename will be different depending on platforms. On Linux it is libhello.so. NINDENT NINDENT This is done by using uv_dlopen to first load the shared library libhello.dylib. Then we get access to the initialize function using uv_dlsym and invoke it. plugin/main.c NDENT 0.0 NDENT 3.5
#include "plugin.h" typedef void (*init_plugin_function)(); void mfp_register(const char *name) { fprintf(stderr, "Registered plugin \e"%s\e"\en", name); } int main(int argc, char **argv) { if (argc == 1) { fprintf(stderr, "Usage: %s [plugin1] [plugin2] ...\en", argv[0]); return 0; } uv_lib_t *lib = (uv_lib_t*) malloc(sizeof(uv_lib_t)); while (--argc) { fprintf(stderr, "Loading %s\en", argv[argc]); if (uv_dlopen(argv[argc], lib)) { fprintf(stderr, "Error: %s\en", uv_dlerror(lib)); continue; } init_plugin_function init_plugin; if (uv_dlsym(lib, "initialize", (void **) &init_plugin)) { fprintf(stderr, "dlsym error: %s\en", uv_dlerror(lib)); continue; } init_plugin(); } return 0; }NINDENT NINDENT uv_dlopen expects a path to the shared library and sets the opaque uv_lib_t pointer. It returns 0 on success, -1 on error. Use uv_dlerror to get the error message. uv_dlsym stores a pointer to the symbol in the second argument in the third argument. init_plugin_function is a function pointer to the sort of function we are looking for in the application\(aqs plugins.
int uv_tty_init(uv_loop_t*, uv_tty_t*, uv_file fd, int unused)NINDENT NINDENT The unused parameter is now auto-detected and ignored. It previously needed to be set to use uv_read_start() on the stream. It is then best to use uv_tty_set_mode to set the mode to normal which enables most TTY formatting, flow-control and other settings. \%Other modes are also available. Remember to call uv_tty_reset_mode when your program exits to restore the state of the terminal. Just good manners. Another set of good manners is to be aware of redirection. If the user redirects the output of your command to a file, control sequences should not be written as they impede readability and grep. To check if the file descriptor is indeed a TTY, call uv_guess_handle with the file descriptor and compare the return value with UV_TTY. Here is a simple example which prints white text on a red background: tty/main.c NDENT 0.0 NDENT 3.5
#include <stdio.h> #include <string.h> #include <unistd.h> #include <uv.h> uv_loop_t *loop; uv_tty_t tty; int main() { loop = uv_default_loop(); uv_tty_init(loop, &tty, STDOUT_FILENO, 0); uv_tty_set_mode(&tty, UV_TTY_MODE_NORMAL); if (uv_guess_handle(1) == UV_TTY) { uv_write_t req; uv_buf_t buf; buf.base = "\e033[41;37m"; buf.len = strlen(buf.base); uv_write(&req, (uv_stream_t*) &tty, &buf, 1, NULL); } uv_write_t req; uv_buf_t buf; buf.base = "Hello TTY\en"; buf.len = strlen(buf.base); uv_write(&req, (uv_stream_t*) &tty, &buf, 1, NULL); uv_tty_reset_mode(); return uv_run(loop, UV_RUN_DEFAULT); }NINDENT NINDENT The final TTY helper is uv_tty_get_winsize() which is used to get the width and height of the terminal and returns 0 on success. Here is a small program which does some animation using the function and character position escape codes. tty-gravity/main.c NDENT 0.0 NDENT 3.5
#include <stdio.h> #include <string.h> #include <unistd.h> #include <uv.h> uv_loop_t *loop; uv_tty_t tty; uv_timer_t tick; uv_write_t write_req; int width, height; int pos = 0; char *message = " Hello TTY "; void update(uv_timer_t *req) { char data[500]; uv_buf_t buf; buf.base = data; buf.len = sprintf(data, "\e033[2J\e033[H\e033[%dB\e033[%luC\e033[42;37m%s", pos, (unsigned long) (width-strlen(message))/2, message); uv_write(&write_req, (uv_stream_t*) &tty, &buf, 1, NULL); pos++; if (pos > height) { uv_tty_reset_mode(); uv_timer_stop(&tick); } } int main() { loop = uv_default_loop(); uv_tty_init(loop, &tty, STDOUT_FILENO, 0); uv_tty_set_mode(&tty, 0); if (uv_tty_get_winsize(&tty, &width, &height)) { fprintf(stderr, "Could not get TTY information\en"); uv_tty_reset_mode(); return 1; } fprintf(stderr, "Width %d, height %d\en", width, height); uv_timer_init(loop, &tick); uv_timer_start(&tick, update, 200, 200); return uv_run(loop, UV_RUN_DEFAULT); }NINDENT NINDENT The escape codes are:
Code |
Meaning |
2 J |
Clear part of the screen, 2 is entire screen |
H |
Moves cursor to certain position, default top-left |
n B |
Moves cursor down by n lines |
n C |
Moves cursor right by n columns |
m |
Obeys string of display settings, in this case green background (40+2), white text (30+7) |
----
0
uv_loop_t* loop = uv_loop_new(); ... uv_loop_delete(loop);NINDENT NINDENT libuv 1.0 NDENT 0.0 NDENT 3.5
uv_loop_t* loop = malloc(sizeof *loop); uv_loop_init(loop); ... uv_loop_close(loop); free(loop);NINDENT NINDENT NOTE: NDENT 0.0 NDENT 3.5 Error handling was omitted for brevity. Check the documentation for uv_loop_init() and uv_loop_close(). NINDENT NINDENT
... assume \(aqserver\(aq is a TCP server which is already listening r = uv_listen((uv_stream_t*) server, 511, NULL); if (r == -1) { uv_err_t err = uv_last_error(uv_default_loop()); /* err.code contains UV_EADDRINUSE */ }NINDENT NINDENT libuv 1.0 NDENT 0.0 NDENT 3.5
... assume \(aqserver\(aq is a TCP server which is already listening r = uv_listen((uv_stream_t*) server, 511, NULL); if (r < 0) { /* r contains UV_EADDRINUSE */ }NINDENT NINDENT
uv_buf_t alloc_cb(uv_handle_t* handle, size_t size) { return uv_buf_init(malloc(size), size); }NINDENT NINDENT In libuv 1.0 a pointer to a buffer is passed to the callback, which the user needs to fill: NDENT 0.0 NDENT 3.5
void alloc_cb(uv_handle_t* handle, size_t size, uv_buf_t* buf) { buf->base = malloc(size); buf->len = size; }NINDENT NINDENT
struct sockaddr_in addr = uv_ip4_addr("0.0.0.0", 1234); ... uv_tcp_bind(&server, addr)NINDENT NINDENT libuv 1.0 NDENT 0.0 NDENT 3.5
struct sockaddr_in addr; uv_ip4_addr("0.0.0.0", 1234, &addr) ... uv_tcp_bind(&server, (const struct sockaddr*) &addr, 0);NINDENT NINDENT The IPv4 and IPv6 struct creating functions (uv_ip4_addr() and uv_ip6_addr()) have also changed, make sure you check the documentation. NDENT 0.0
..note:: This change applies to all functions that made a distinction between IPv4 and IPv6 addresses. NINDENT
void on_read(uv_stream_t* handle, ssize_t nread, uv_buf_t buf) { ... } void recv_cb(uv_udp_t* handle, ssize_t nread, uv_buf_t buf, struct sockaddr* addr, unsigned flags) { ... }NINDENT NINDENT libuv 1.0 NDENT 0.0 NDENT 3.5
void on_read(uv_stream_t* handle, ssize_t nread, const uv_buf_t* buf) { ... } void recv_cb(uv_udp_t* handle, ssize_t nread, const uv_buf_t* buf, const struct sockaddr* addr, unsigned flags) { ... }NINDENT NINDENT
void on_read(uv_pipe_t* pipe, ssize_t nread, uv_buf_t buf, uv_handle_type pending) { ... }NINDENT NINDENT In libuv 1.0, uv_read2_start was removed, and the user needs to check if there are pending handles using uv_pipe_pending_count() and uv_pipe_pending_type() while in the read callback: NDENT 0.0 NDENT 3.5
void on_read(uv_stream_t* handle, ssize_t nread, const uv_buf_t* buf) { ... while (uv_pipe_pending_count((uv_pipe_t*) handle) != 0) { pending = uv_pipe_pending_type((uv_pipe_t*) handle); ... } ... }NINDENT NINDENT
fd = handle->io_watcher.fd;NINDENT NINDENT This is now properly exposed through the uv_fileno() function.
.