提交 bf64e784 authored 作者: Iñaki Baz Castillo's avatar Iñaki Baz Castillo

- Fix an issue in `buffer.toString()` that makes mediasoup fail in Node 8.

- Update libuv to version 1.12.0.
上级 303d5c72
......@@ -98,21 +98,21 @@ class Channel extends EventEmitter
// 68 = 'D' (a debug log).
case 68:
workerLogger.debug(nsPayload.toString(null, 1));
workerLogger.debug(nsPayload.toString('utf8', 1));
break;
// 87 = 'W' (a warning log).
case 87:
workerLogger.warn(nsPayload.toString(null, 1));
workerLogger.warn(nsPayload.toString('utf8', 1));
break;
// 69 = 'E' (an error log).
case 69:
workerLogger.error(nsPayload.toString(null, 1));
workerLogger.error(nsPayload.toString('utf8', 1));
break;
default:
workerLogger.error('unexpected data: %s', nsPayload.toString());
workerLogger.error('unexpected data: %s', nsPayload.toString('utf8'));
}
}
catch (error)
......
<!--
If you want to report a bug, you are in the right place!
If you need help or have a question, go here: https://github.com/libuv/help/new
Please include code that demonstrates the bug and keep it short and simple.
-->
* **Version**: <!-- libuv version -->
* **Platform**: <!-- `uname -a` (UNIX), or Windows version and machine type -->
A. Hauptmann <andreashauptmann@t-online.de>
Aaron Bieber <qbit@deftly.net> <deftly@gmail.com>
Alan Gutierrez <alan@prettyrobots.com> <alan@blogometer.com>
Andrius Bentkus <andrius.bentkus@gmail.com> <toxedvirus@gmail.com>
......@@ -39,3 +40,4 @@ Timothy J. Fontaine <tjfontaine@gmail.com>
Yasuhiro Matsumoto <mattn.jp@gmail.com>
Yazhong Liu <yorkiefixer@gmail.com>
Yuki Okumura <mjt@cltn.org>
jBarz <jBarz@users.noreply.github.com> <jbarboza@ca.ibm.com>
......@@ -284,3 +284,11 @@ muflub <admin@lodle.net>
Daniel Bevenius <daniel.bevenius@gmail.com>
Howard Hellyer <hhellyer@uk.ibm.com>
Chris Araman <chris.araman@fuze.com>
Vladimir Matveev <vladima@microsoft.com>
Jason Madden <jamadden@gmail.com>
Jamie Davis <davisjam@vt.edu>
Daniel Kahn Gillmor <dkg@fifthhorseman.net>
Keane <erich.keane@intel.com>
James McCoy <jamessan@jamessan.com>
Bernardo Ramos <berna.gensis@gmail.com>
Juan Cruz Viotti <jviotti@openmailbox.org>
2017.02.02, Version 1.11.0 (Stable)
2017.05.31, Version 1.12.0 (Stable)
Changes since version 1.11.0:
* Now working on version 1.11.1 (cjihrig)
* test: fix tests on OpenBSD (Santiago Gimeno)
* test: fix -Wformat warning (Santiago Gimeno)
* win,fs: avoid double freeing uv_fs_event_t.dirw (Vladimir Matveev)
* unix: remove unused code in `uv__io_start` (Fedor Indutny)
* signal: add uv_signal_start_oneshot method (Santiago Gimeno)
* unix: factor out reusable POSIX hrtime impl (Brad King)
* unix,win: add uv_os_{get,set,unset}env() (cjihrig)
* win: add uv__convert_utf8_to_utf16() (cjihrig)
* docs: improve UV_ENOBUFS scenario documentation (cjihrig)
* unix: return UV_EINVAL for NULL env name (jBarz)
* unix: filter getifaddrs results consistently (Brad King)
* unix: factor out getifaddrs result filter (Brad King)
* unix: factor out reusable BSD ifaddrs impl (Brad King)
* unix: use union to follow strict aliasing rules (jBarz)
* unix: simplify async watcher dispatch logic (Ben Noordhuis)
* samples: update timer callback prototype (Ben Noordhuis)
* unix: make loops and watchers usable after fork() (Jason Madden)
* win: free uv__loops once empty (cjihrig)
* tools: add make_dist_html.py script (Ben Noordhuis)
* win,sunos: stop handle on uv_fs_event_start() err (cjihrig)
* unix,windows: refactor request init logic (Ben Noordhuis)
* win: fix memory leak inside uv__pipe_getname (A. Hauptmann)
* fsevent: support for files without short name (Bartosz Sosnowski)
* doc: fix multiple doc typos (Jamie Davis)
* test,osx: fix flaky kill test (Santiago Gimeno)
* unix: inline uv_pipe_bind() err_bind goto target (cjihrig)
* unix,test: deadstore fixes (Rasmus Christian Pedersen)
* win: fix memory leak inside uv_fs_access() (A. Hauptmann)
* doc: fix docs/src/fs.rst build warning (Daniel Bevenius)
* doc: minor grammar fix in Installation section (Daniel Bevenius)
* doc: suggestions for design page (Daniel Bevenius)
* doc: libuv does not touch uv_loop_t.data (Ben Noordhuis)
* github: add ISSUE_TEMPLATE.md (Ben Noordhuis)
* doc: add link to libuv/help to README (Ben Noordhuis)
* udp: fix fast path in uv_udp_send() on unix (Fedor Indutny)
* test: add test for uv_udp_send() fix (Trevor Norris)
* doc: fix documentation for uv_handle_t.type (Daniel Kahn Gillmor)
* zos: use proper prototype for epoll_init() (Ben Noordhuis)
* doc: rename docs to "libuv documentation" (Saúl Ibarra Corretgé)
* doc: update copyright years (Saúl Ibarra Corretgé)
* doc: move TOC to a dedicated document (Saúl Ibarra Corretgé)
* doc: move documentation section up (Saúl Ibarra Corretgé)
* doc: move "upgrading" to a standalone document (Saúl Ibarra Corretgé)
* doc: add initial version of the User Guide (Saúl Ibarra Corretgé)
* doc: removed unused file (Saúl Ibarra Corretgé)
* doc: update guide/about and mention new maintainership (Saúl Ibarra Corretgé)
* doc: remove licensing note from guide/about (Saúl Ibarra Corretgé)
* doc: add warning note to user guide (Saúl Ibarra Corretgé)
* doc: change license to CC BY 4.0 (Saúl Ibarra Corretgé)
* doc: remove ubvook reference from README (Saúl Ibarra Corretgé)
* doc: add code samples from uvbook (unadapted) (Saúl Ibarra Corretgé)
* doc: update supported linux/glibc baseline (Ben Noordhuis)
* win: avoid leaking pipe handles to child processes (Jameson Nash)
* win,test: support stdout output larger than 1kb (Bartosz Sosnowski)
* win: remove __declspec(inline) from atomic op (Keane)
* test: fix VC++ compilation warning (Rasmus Christian Pedersen)
* build: add -Wstrict-prototypes (Jameson Nash)
* zos: implement uv__io_fork, skip fs event tests (jBarz)
* unix: do not close udp sockets on bind error (Marc Schlaich)
* unix: remove FSEventStreamFlushSync() call (cjihrig)
* build,openbsd: remove kvm-related code (James McCoy)
* test: fix flaky tcp-write-queue-order (Santiago Gimeno)
* unix,win: add uv_os_gethostname() (cjihrig)
* zos: increase timeout for tcp_writealot (jBarz)
* zos: do not inline OOB data by default (jBarz)
* test: fix -Wstrict-prototypes compiler warnings (Ben Noordhuis)
* unix: factor out reusable no-proctitle impl (Brad King)
* test: factor out fsevents skip explanation (Brad King)
* test: skip fork fsevent cases when lacking support (Brad King)
* unix: factor out reusable no-fsevents impl (Brad King)
* unix: factor out reusable sysinfo memory lookup (Brad King)
* unix: factor out reusable sysinfo loadavg impl (Brad King)
* unix: factor out reusable procfs exepath impl (Brad King)
* unix: add a uv__io_poll impl using POSIX poll(2) (Brad King)
* cygwin: implement support for cygwin and msys2 (Brad King)
* cygwin: recognize EOF on named pipe closure (Brad King)
* cygwin: fix uv_pipe_connect report of ENOTSOCK (Brad King)
* cygwin: disable non-functional ipc handle send (Brad King)
* test: skip self-connecting tests on cygwin (Brad King)
* doc: mark uv_loop_fork() as experimental (cjihrig)
* doc: add bzoz to maintainers (Bartosz Sosnowski)
* doc: fix memory leak in tcp-echo-server example (Bernardo Ramos)
* win: make uv__get_osfhandle() public (Juan Cruz Viotti)
* doc: use valid pipe name in pipe-echo-server (Bernardo Ramos)
2017.02.02, Version 1.11.0 (Stable), 7452ef4e06a4f99ee26b694c65476401534f2725
Changes since version 1.10.2:
......
差异被折叠。
......@@ -3,6 +3,7 @@
libuv is currently managed by the following individuals:
* **Bartosz Sosnowski** ([@bzoz](https://github.com/bzoz))
* **Ben Noordhuis** ([@bnoordhuis](https://github.com/bnoordhuis))
- GPG key: D77B 1E34 243F BAF0 5F8E 9CC3 4F55 C8C8 46AB 89B9 (pubkey-bnoordhuis)
* **Bert Belder** ([@piscisaureus](https://github.com/piscisaureus))
......
......@@ -166,16 +166,19 @@ test_run_tests_SOURCES = test/blackhole-server.c \
test/test-eintr-handling.c \
test/test-embed.c \
test/test-emfile.c \
test/test-env-vars.c \
test/test-error.c \
test/test-fail-always.c \
test/test-fs-event.c \
test/test-fs-poll.c \
test/test-fs.c \
test/test-fork.c \
test/test-get-currentexe.c \
test/test-get-loadavg.c \
test/test-get-memory.c \
test/test-get-passwd.c \
test/test-getaddrinfo.c \
test/test-gethostname.c \
test/test-getnameinfo.c \
test/test-getsockname.c \
test/test-handle-fileno.c \
......@@ -272,6 +275,7 @@ test_run_tests_SOURCES = test/blackhole-server.c \
test/test-udp-open.c \
test/test-udp-options.c \
test/test-udp-send-and-recv.c \
test/test-udp-send-hang-loop.c \
test/test-udp-send-immediate.c \
test/test-udp-send-unreachable.c \
test/test-udp-try-send.c \
......@@ -333,12 +337,26 @@ libuv_la_SOURCES += src/unix/android-ifaddrs.c \
src/unix/pthread-barrier.c
endif
if CYGWIN
libuv_la_CFLAGS += -D_GNU_SOURCE
libuv_la_SOURCES += src/unix/cygwin.c \
src/unix/bsd-ifaddrs.c \
src/unix/no-fsevents.c \
src/unix/no-proctitle.c \
src/unix/posix-hrtime.c \
src/unix/posix-poll.c \
src/unix/procfs-exepath.c \
src/unix/sysinfo-loadavg.c \
src/unix/sysinfo-memory.c
endif
if DARWIN
include_HEADERS += include/uv-darwin.h \
include/pthread-barrier.h
libuv_la_CFLAGS += -D_DARWIN_USE_64_BIT_INODE=1
libuv_la_CFLAGS += -D_DARWIN_UNLIMITED_SELECT=1
libuv_la_SOURCES += src/unix/darwin.c \
libuv_la_SOURCES += src/unix/bsd-ifaddrs.c \
src/unix/darwin.c \
src/unix/darwin-proctitle.c \
src/unix/fsevents.c \
src/unix/kqueue.c \
......@@ -349,13 +367,19 @@ endif
if DRAGONFLY
include_HEADERS += include/uv-bsd.h
libuv_la_SOURCES += src/unix/freebsd.c src/unix/kqueue.c
libuv_la_SOURCES += src/unix/bsd-ifaddrs.c \
src/unix/freebsd.c \
src/unix/kqueue.c \
src/unix/posix-hrtime.c
test_run_tests_LDFLAGS += -lutil
endif
if FREEBSD
include_HEADERS += include/uv-bsd.h
libuv_la_SOURCES += src/unix/freebsd.c src/unix/kqueue.c
libuv_la_SOURCES += src/unix/bsd-ifaddrs.c \
src/unix/freebsd.c \
src/unix/kqueue.c \
src/unix/posix-hrtime.c
test_run_tests_LDFLAGS += -lutil
endif
......@@ -366,26 +390,49 @@ libuv_la_SOURCES += src/unix/linux-core.c \
src/unix/linux-inotify.c \
src/unix/linux-syscalls.c \
src/unix/linux-syscalls.h \
src/unix/proctitle.c
src/unix/procfs-exepath.c \
src/unix/proctitle.c \
src/unix/sysinfo-loadavg.c \
src/unix/sysinfo-memory.c
test_run_tests_LDFLAGS += -lutil
endif
if MSYS
libuv_la_CFLAGS += -D_GNU_SOURCE
libuv_la_SOURCES += src/unix/cygwin.c \
src/unix/bsd-ifaddrs.c \
src/unix/no-fsevents.c \
src/unix/no-proctitle.c \
src/unix/posix-hrtime.c \
src/unix/posix-poll.c \
src/unix/procfs-exepath.c \
src/unix/sysinfo-loadavg.c \
src/unix/sysinfo-memory.c
endif
if NETBSD
include_HEADERS += include/uv-bsd.h
libuv_la_SOURCES += src/unix/kqueue.c src/unix/netbsd.c
libuv_la_SOURCES += src/unix/bsd-ifaddrs.c \
src/unix/kqueue.c \
src/unix/netbsd.c \
src/unix/posix-hrtime.c
test_run_tests_LDFLAGS += -lutil
endif
if OPENBSD
include_HEADERS += include/uv-bsd.h
libuv_la_SOURCES += src/unix/kqueue.c src/unix/openbsd.c
libuv_la_SOURCES += src/unix/bsd-ifaddrs.c \
src/unix/kqueue.c \
src/unix/openbsd.c \
src/unix/posix-hrtime.c
test_run_tests_LDFLAGS += -lutil
endif
if SUNOS
include_HEADERS += include/uv-sunos.h
libuv_la_CFLAGS += -D__EXTENSIONS__ -D_XOPEN_SOURCE=500
libuv_la_SOURCES += src/unix/sunos.c
libuv_la_SOURCES += src/unix/no-proctitle.c \
src/unix/sunos.c
endif
if OS390
......@@ -407,6 +454,7 @@ libuv_la_CFLAGS += -D_UNIX03_THREADS \
libuv_la_LDFLAGS += -qXPLINK
libuv_la_SOURCES += src/unix/pthread-fixes.c \
src/unix/pthread-barrier.c \
src/unix/no-fsevents.c \
src/unix/os390.c \
src/unix/os390-syscalls.c \
src/unix/proctitle.c
......
......@@ -17,6 +17,7 @@ CC ?= gcc
CFLAGS += -Wall \
-Wextra \
-Wno-unused-parameter \
-Wstrict-prototypes \
-Iinclude \
-Isrc \
-Isrc/win \
......
......@@ -44,15 +44,17 @@ The ABI/API changes can be tracked [here](http://abi-laboratory.pro/tracker/time
## Licensing
libuv is licensed under the MIT license. Check the [LICENSE file](LICENSE).
The documentation is licensed under the CC BY 4.0 license. Check the [LICENSE-docs file](LICENSE-docs).
## Community
* [Support](https://github.com/libuv/help)
* [Mailing list](http://groups.google.com/group/libuv)
* [IRC chatroom (#libuv@irc.freenode.org)](http://webchat.freenode.net?channels=libuv&uio=d4)
## Documentation
### Official API documentation
### Official documentation
Located in the docs/ subdirectory. It uses the [Sphinx](http://sphinx-doc.org/)
framework, which makes it possible to build the documentation in multiple
......@@ -88,8 +90,6 @@ also serve as API specification and usage examples.
### Other resources
* [An Introduction to libuv](http://nikhilm.github.com/uvbook/)
&mdash; An overview of libuv with tutorials.
* [LXJS 2012 talk](http://www.youtube.com/watch?v=nGn60vDSxQ4)
&mdash; High-level introductory talk about libuv.
* [libuv-dox](https://github.com/thlorenz/libuv-dox)
......
......@@ -2,7 +2,7 @@
| System | Support type | Supported versions | Notes |
|---|---|---|---|
| GNU/Linux | Tier 1 | Linux >= 2.6.18 with glibc >= 2.5 | |
| GNU/Linux | Tier 1 | Linux >= 2.6.32 with glibc >= 2.12 | |
| macOS | Tier 1 | macOS >= 10.7 | |
| Windows | Tier 1 | Windows >= XP SP1 | MSVC 2008 and later are supported |
| FreeBSD | Tier 1 | >= 9 (see note) | |
......
version: v1.11.0.build{build}
version: v1.12.0.build{build}
install:
- cinst -y nsis
......
......@@ -93,6 +93,7 @@ test/test-cwd-and-chdir.c
test/test-delayed-accept.c
test/test-dlerror.c
test/test-embed.c
test/test-env-vars.c
test/test-error.c
test/test-fail-always.c
test/test-fs-event.c
......@@ -103,6 +104,7 @@ test/test-get-loadavg.c
test/test-get-memory.c
test/test-get-passwd.c
test/test-getaddrinfo.c
test/test-gethostname.c
test/test-getsockname.c
test/test-homedir.c
test/test-hrtime.c
......@@ -165,6 +167,7 @@ test/test-udp-multicast-ttl.c
test/test-udp-open.c
test/test-udp-options.c
test/test-udp-send-and-recv.c
test/test-udp-send-hang-loop.c
test/test-walk-handles.c
test/test-watcher-cross-stop.c
"
......
......@@ -180,6 +180,7 @@
'-Wendif-labels',
'-W',
'-Wno-unused-parameter',
'-Wstrict-prototypes',
],
},
'conditions': [
......
......@@ -13,7 +13,7 @@
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
AC_PREREQ(2.57)
AC_INIT([libuv], [1.11.0], [https://github.com/libuv/libuv/issues])
AC_INIT([libuv], [1.12.0], [https://github.com/libuv/libuv/issues])
AC_CONFIG_MACRO_DIR([m4])
m4_include([m4/libuv-extra-automake-flags.m4])
m4_include([m4/as_case.m4])
......@@ -33,6 +33,7 @@ CC_CHECK_CFLAGS_APPEND([-std=gnu89])
CC_CHECK_CFLAGS_APPEND([-Wall])
CC_CHECK_CFLAGS_APPEND([-Wextra])
CC_CHECK_CFLAGS_APPEND([-Wno-unused-parameter])
CC_CHECK_CFLAGS_APPEND([-Wstrict-prototypes])
# AM_PROG_AR is not available in automake v0.11 but it's essential in v0.12.
m4_ifdef([AM_PROG_AR], [AM_PROG_AR])
# autoconf complains if AC_PROG_LIBTOOL precedes AM_PROG_AR.
......@@ -42,7 +43,6 @@ LT_INIT
# TODO(bnoordhuis) Check for -pthread vs. -pthreads
AC_CHECK_LIB([dl], [dlopen])
AC_CHECK_LIB([kstat], [kstat_lookup])
AC_CHECK_LIB([kvm], [kvm_open])
AC_CHECK_LIB([nsl], [gethostbyname])
AC_CHECK_LIB([perfstat], [perfstat_cpu])
AC_CHECK_LIB([pthread], [pthread_mutex_init])
......@@ -52,10 +52,12 @@ AC_CHECK_LIB([socket], [socket])
AC_SYS_LARGEFILE
AM_CONDITIONAL([AIX], [AS_CASE([$host_os],[aix*], [true], [false])])
AM_CONDITIONAL([ANDROID], [AS_CASE([$host_os],[linux-android*],[true], [false])])
AM_CONDITIONAL([CYGWIN], [AS_CASE([$host_os],[cygwin*], [true], [false])])
AM_CONDITIONAL([DARWIN], [AS_CASE([$host_os],[darwin*], [true], [false])])
AM_CONDITIONAL([DRAGONFLY],[AS_CASE([$host_os],[dragonfly*], [true], [false])])
AM_CONDITIONAL([FREEBSD], [AS_CASE([$host_os],[*freebsd*], [true], [false])])
AM_CONDITIONAL([LINUX], [AS_CASE([$host_os],[linux*], [true], [false])])
AM_CONDITIONAL([MSYS], [AS_CASE([$host_os],[msys*], [true], [false])])
AM_CONDITIONAL([NETBSD], [AS_CASE([$host_os],[netbsd*], [true], [false])])
AM_CONDITIONAL([OPENBSD], [AS_CASE([$host_os],[openbsd*], [true], [false])])
AM_CONDITIONAL([OS390], [AS_CASE([$host_os],[openedition*], [true], [false])])
......@@ -64,6 +66,9 @@ AM_CONDITIONAL([WINNT], [AS_CASE([$host_os],[mingw*], [true], [false])
AS_CASE([$host_os],[mingw*], [
LIBS="$LIBS -lws2_32 -lpsapi -liphlpapi -lshell32 -luserenv -luser32"
])
AS_CASE([$host_os], [openbsd*], [], [
AC_CHECK_LIB([kvm], [kvm_open])
])
AC_CHECK_HEADERS([sys/ahafs_evProds.h])
AC_CHECK_PROG(PKG_CONFIG, pkg-config, yes)
AM_CONDITIONAL([HAVE_PKG_CONFIG], [test "x$PKG_CONFIG" != "x"])
......
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <uv.h>
uv_loop_t *loop;
uv_process_t child_req;
uv_process_options_t options;
void cleanup_handles(uv_process_t *req, int64_t exit_status, int term_signal) {
fprintf(stderr, "Process exited with status %" PRId64 ", signal %d\n", exit_status, term_signal);
uv_close((uv_handle_t*) req->data, NULL);
uv_close((uv_handle_t*) req, NULL);
}
void invoke_cgi_script(uv_tcp_t *client) {
size_t size = 500;
char path[size];
uv_exepath(path, &size);
strcpy(path + (strlen(path) - strlen("cgi")), "tick");
char* args[2];
args[0] = path;
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\n", uv_strerror(r));
return;
}
}
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);
}
}
int main() {
loop = uv_default_loop();
uv_tcp_t server;
uv_tcp_init(loop, &server);
struct sockaddr_in bind_addr;
uv_ip4_addr("0.0.0.0", 7000, &bind_addr);
uv_tcp_bind(&server, (const struct sockaddr *)&bind_addr, 0);
int r = uv_listen((uv_stream_t*) &server, 128, on_new_connection);
if (r) {
fprintf(stderr, "Listen error %s\n", uv_err_name(r));
return 1;
}
return uv_run(loop, UV_RUN_DEFAULT);
}
#include <stdio.h>
#include <unistd.h>
int main() {
int i;
for (i = 0; i < 10; i++) {
printf("tick\n");
fflush(stdout);
sleep(1);
}
printf("BOOM!\n");
return 0;
}
#include <stdio.h>
#include <uv.h>
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] = "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\n", uv_strerror(r));
return 1;
}
fprintf(stderr, "Launched sleep with PID %d\n", child_req.pid);
uv_unref((uv_handle_t*) &child_req);
return uv_run(loop, UV_RUN_DEFAULT);
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <uv.h>
uv_loop_t *loop;
void alloc_buffer(uv_handle_t *handle, size_t suggested_size, uv_buf_t *buf) {
buf->base = malloc(suggested_size);
buf->len = suggested_size;
}
void on_read(uv_stream_t *client, ssize_t nread, const uv_buf_t *buf) {
if (nread < 0) {
if (nread != UV_EOF)
fprintf(stderr, "Read error %s\n", uv_err_name(nread));
uv_close((uv_handle_t*) client, NULL);
free(buf->base);
free(client);
return;
}
char *data = (char*) malloc(sizeof(char) * (nread+1));
data[nread] = '\0';
strncpy(data, buf->base, nread);
fprintf(stderr, "%s", data);
free(data);
free(buf->base);
}
void on_connect(uv_connect_t *req, int status) {
if (status < 0) {
fprintf(stderr, "connect failed error %s\n", uv_err_name(status));
free(req);
return;
}
uv_read_start((uv_stream_t*) req->handle, alloc_buffer, on_read);
free(req);
}
void on_resolved(uv_getaddrinfo_t *resolver, int status, struct addrinfo *res) {
if (status < 0) {
fprintf(stderr, "getaddrinfo callback error %s\n", uv_err_name(status));
return;
}
char addr[17] = {'\0'};
uv_ip4_name((struct sockaddr_in*) res->ai_addr, addr, 16);
fprintf(stderr, "%s\n", 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);
}
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\n", uv_err_name(r));
return 1;
}
return uv_run(loop, UV_RUN_DEFAULT);
}
#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.\n");
uv_run(loop, UV_RUN_DEFAULT);
uv_loop_close(loop);
free(loop);
return 0;
}
#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...\n");
uv_run(uv_default_loop(), UV_RUN_DEFAULT);
uv_loop_close(uv_default_loop());
return 0;
}
#include <stdio.h>
#include <uv.h>
uv_loop_t *loop;
uv_fs_t stdin_watcher;
uv_idle_t idler;
char buffer[1024];
void crunch_away(uv_idle_t* handle) {
// Compute extra-terrestrial life
// fold proteins
// computer another digit of PI
// or similar
fprintf(stderr, "Computing PI...\n");
// just to avoid overwhelming your terminal emulator
uv_idle_stop(handle);
}
void on_type(uv_fs_t *req) {
if (stdin_watcher.result > 0) {
buffer[stdin_watcher.result] = '\0';
printf("Typed %s\n", buffer);
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);
}
else if (stdin_watcher.result < 0) {
fprintf(stderr, "error opening file: %s\n", uv_strerror(req->result));
}
}
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);
}
#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\n", count);
while (i--) {
uv_interface_address_t interface = info[i];
printf("Name: %s\n", interface.name);
printf("Internal? %s\n", 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\n", buf);
}
else if (interface.address.address4.sin_family == AF_INET6) {
uv_ip6_name(&interface.address.address6, buf, sizeof(buf));
printf("IPv6 address: %s\n", buf);
}
printf("\n");
}
uv_free_interface_addresses(info, count);
return 0;
}
#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\n", num);
printf("Reader %d: shared num = %d\n", num, shared_num);
uv_rwlock_rdunlock(&numlock);
printf("Reader %d: released lock\n", 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\n", num);
shared_num++;
printf("Writer %d: incremented shared num = %d\n", num, shared_num);
uv_rwlock_wrunlock(&numlock);
printf("Writer %d: released lock\n", 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;
}
var net = require('net');
var PHRASE = "hello world";
var write = function(socket) {
socket.write(PHRASE, 'utf8');
}
for (var i = 0; i < 1000; i++) {
(function() {
var socket = net.connect(7000, 'localhost', function() {
socket.on('data', function(reply) {
if (reply.toString().indexOf(PHRASE) != 0)
console.error("Problem! '" + reply + "'" + " '" + PHRASE + "'");
else
write(socket);
});
write(socket);
});
})();
}
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <uv.h>
uv_loop_t *loop;
struct child_worker {
uv_process_t req;
uv_process_options_t options;
uv_pipe_t pipe;
} *workers;
int round_robin_counter;
int child_worker_count;
uv_buf_t dummy_buf;
char worker_path[500];
void close_process_handle(uv_process_t *req, int64_t exit_status, int term_signal) {
fprintf(stderr, "Process exited with status %" PRId64 ", signal %d\n", exit_status, term_signal);
uv_close((uv_handle_t*) req, NULL);
}
void alloc_buffer(uv_handle_t *handle, size_t suggested_size, uv_buf_t *buf) {
buf->base = malloc(suggested_size);
buf->len = suggested_size;
}
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);
}
}
void setup_workers() {
size_t path_size = 500;
uv_exepath(worker_path, &path_size);
strcpy(worker_path + (strlen(worker_path) - strlen("multi-echo-server")), "worker");
fprintf(stderr, "Worker path: %s\n", worker_path);
char* args[2];
args[0] = worker_path;
args[1] = NULL;
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(sizeof(struct child_worker), cpu_count);
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\n", worker->req.pid);
}
}
int main() {
loop = uv_default_loop();
setup_workers();
uv_tcp_t server;
uv_tcp_init(loop, &server);
struct sockaddr_in bind_addr;
uv_ip4_addr("0.0.0.0", 7000, &bind_addr);
uv_tcp_bind(&server, (const struct sockaddr *)&bind_addr, 0);
int r;
if ((r = uv_listen((uv_stream_t*) &server, 128, on_new_connection))) {
fprintf(stderr, "Listen error %s\n", uv_err_name(r));
return 2;
}
return uv_run(loop, UV_RUN_DEFAULT);
}
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <uv.h>
uv_loop_t *loop;
uv_pipe_t queue;
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 alloc_buffer(uv_handle_t *handle, size_t suggested_size, uv_buf_t *buf) {
buf->base = malloc(suggested_size);
buf->len = suggested_size;
}
void echo_write(uv_write_t *req, int status) {
if (status) {
fprintf(stderr, "Write error %s\n", uv_err_name(status));
}
free_write_req(req);
}
void echo_read(uv_stream_t *client, ssize_t nread, const uv_buf_t *buf) {
if (nread > 0) {
write_req_t *req = (write_req_t*) malloc(sizeof(write_req_t));
req->buf = uv_buf_init(buf->base, nread);
uv_write((uv_write_t*) req, client, &req->buf, 1, echo_write);
return;
}
if (nread < 0) {
if (nread != UV_EOF)
fprintf(stderr, "Read error %s\n", uv_err_name(nread));
uv_close((uv_handle_t*) client, NULL);
}
free(buf->base);
}
void on_new_connection(uv_stream_t *q, ssize_t nread, const uv_buf_t *buf) {
if (nread < 0) {
if (nread != UV_EOF)
fprintf(stderr, "Read error %s\n", 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\n");
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\n", getpid(), fd);
uv_read_start((uv_stream_t*) client, alloc_buffer, echo_read);
}
else {
uv_close((uv_handle_t*) client, NULL);
}
}
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);
}
#include <stdio.h>
#include <stdlib.h>
#include <uv.h>
uv_loop_t *loop;
const char *command;
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] = '\0';
fprintf(stderr, "Change detected in %s: ", path);
if (events & UV_RENAME)
fprintf(stderr, "renamed");
if (events & UV_CHANGE)
fprintf(stderr, "changed");
fprintf(stderr, " %s\n", filename ? filename : "");
system(command);
}
int main(int argc, char **argv) {
if (argc <= 2) {
fprintf(stderr, "Usage: %s <command> <file1> [file2 ...]\n", argv[0]);
return 1;
}
loop = uv_default_loop();
command = argv[1];
while (argc-- > 2) {
fprintf(stderr, "Adding watch on %s\n", 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);
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <uv.h>
#ifdef _WIN32
#define PIPENAME "\\\\?\\pipe\\echo.sock"
#else
#define PIPENAME "/tmp/echo.sock"
#endif
uv_loop_t *loop;
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 alloc_buffer(uv_handle_t *handle, size_t suggested_size, uv_buf_t *buf) {
buf->base = malloc(suggested_size);
buf->len = suggested_size;
}
void echo_write(uv_write_t *req, int status) {
if (status < 0) {
fprintf(stderr, "Write error %s\n", uv_err_name(status));
}
free_write_req(req);
}
void echo_read(uv_stream_t *client, ssize_t nread, const uv_buf_t *buf) {
if (nread > 0) {
write_req_t *req = (write_req_t*) malloc(sizeof(write_req_t));
req->buf = uv_buf_init(buf->base, nread);
uv_write((uv_write_t*) req, client, &req->buf, 1, echo_write);
return;
}
if (nread < 0) {
if (nread != UV_EOF)
fprintf(stderr, "Read error %s\n", uv_err_name(nread));
uv_close((uv_handle_t*) client, NULL);
}
free(buf->base);
}
void on_new_connection(uv_stream_t *server, int status) {
if (status == -1) {
// error!
return;
}
uv_pipe_t *client = (uv_pipe_t*) malloc(sizeof(uv_pipe_t));
uv_pipe_init(loop, client, 0);
if (uv_accept(server, (uv_stream_t*) client) == 0) {
uv_read_start((uv_stream_t*) client, alloc_buffer, echo_read);
}
else {
uv_close((uv_handle_t*) client, NULL);
}
}
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\n", uv_err_name(r));
return 1;
}
if ((r = uv_listen((uv_stream_t*) &server, 128, on_new_connection))) {
fprintf(stderr, "Listen error %s\n", uv_err_name(r));
return 2;
}
return uv_run(loop, UV_RUN_DEFAULT);
}
#include "plugin.h"
void initialize() {
mfp_register("Hello World!");
}
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <uv.h>
#include "plugin.h"
typedef void (*init_plugin_function)();
void mfp_register(const char *name) {
fprintf(stderr, "Registered plugin \"%s\"\n", name);
}
int main(int argc, char **argv) {
if (argc == 1) {
fprintf(stderr, "Usage: %s [plugin1] [plugin2] ...\n", argv[0]);
return 0;
}
uv_lib_t *lib = (uv_lib_t*) malloc(sizeof(uv_lib_t));
while (--argc) {
fprintf(stderr, "Loading %s\n", argv[argc]);
if (uv_dlopen(argv[argc], lib)) {
fprintf(stderr, "Error: %s\n", uv_dlerror(lib));
continue;
}
init_plugin_function init_plugin;
if (uv_dlsym(lib, "initialize", (void **) &init_plugin)) {
fprintf(stderr, "dlsym error: %s\n", uv_dlerror(lib));
continue;
}
init_plugin();
}
return 0;
}
#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);
#endif
#include <stdio.h>
#include <string.h>
#include <inttypes.h>
#include <uv.h>
uv_loop_t *loop;
uv_process_t child_req;
uv_process_options_t options;
void on_exit(uv_process_t *req, int64_t exit_status, int term_signal) {
fprintf(stderr, "Process exited with status %" PRId64 ", signal %d\n", exit_status, term_signal);
uv_close((uv_handle_t*) req, NULL);
}
int main() {
loop = uv_default_loop();
size_t size = 500;
char path[size];
uv_exepath(path, &size);
strcpy(path + (strlen(path) - strlen("proc-streams")), "test");
char* args[2];
args[0] = path;
args[1] = NULL;
/* ... */
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\n", uv_strerror(r));
return 1;
}
return uv_run(loop, UV_RUN_DEFAULT);
}
#include <stdio.h>
int main()
{
fprintf(stderr, "This is stderr\n");
printf("This is stdout\n");
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <uv.h>
uv_loop_t *loop;
uv_async_t async;
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;
}
}
void after(uv_work_t *req, int status) {
fprintf(stderr, "Download complete\n");
uv_close((uv_handle_t*) &async, NULL);
}
void print_progress(uv_async_t *handle) {
double percentage = *((double*) handle->data);
fprintf(stderr, "Downloaded %.2f%%\n", percentage);
}
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);
}
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <uv.h>
#define FIB_UNTIL 25
uv_loop_t *loop;
uv_work_t fib_reqs[FIB_UNTIL];
long fib_(long t) {
if (t == 0 || t == 1)
return 1;
else
return fib_(t-1) + fib_(t-2);
}
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\n", n, fib);
}
void after_fib(uv_work_t *req, int status) {
if (status == UV_ECANCELED)
fprintf(stderr, "Calculation of %d cancelled.\n", *(int *) req->data);
}
void signal_handler(uv_signal_t *req, int signum)
{
printf("Signal received!\n");
int i;
for (i = 0; i < FIB_UNTIL; i++) {
uv_cancel((uv_req_t*) &fib_reqs[i]);
}
uv_signal_stop(req);
}
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);
}
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <uv.h>
#define FIB_UNTIL 25
uv_loop_t *loop;
long fib_(long t) {
if (t == 0 || t == 1)
return 1;
else
return fib_(t-1) + fib_(t-2);
}
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\n", n, fib);
}
void after_fib(uv_work_t *req, int status) {
fprintf(stderr, "Done calculating %dth fibonacci\n", *(int *) req->data);
}
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);
}
#include <stdio.h>
#include <uv.h>
uv_loop_t *loop;
uv_timer_t gc_req;
uv_timer_t fake_job_req;
void gc(uv_timer_t *handle) {
fprintf(stderr, "Freeing unused objects\n");
}
void fake_job(uv_timer_t *handle) {
fprintf(stdout, "Fake job done\n");
}
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);
}
#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\n", 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\n", 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;
}
#include <stdio.h>
#include <inttypes.h>
#include <uv.h>
uv_loop_t *loop;
uv_process_t child_req;
uv_process_options_t options;
void on_exit(uv_process_t *req, int64_t exit_status, int term_signal) {
fprintf(stderr, "Process exited with status %" PRId64 ", signal %d\n", exit_status, term_signal);
uv_close((uv_handle_t*) req, NULL);
}
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\n", uv_strerror(r));
return 1;
} else {
fprintf(stderr, "Launched process with ID %d\n", child_req.pid);
}
return uv_run(loop, UV_RUN_DEFAULT);
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <uv.h>
#define DEFAULT_PORT 7000
#define DEFAULT_BACKLOG 128
uv_loop_t *loop;
struct sockaddr_in addr;
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 alloc_buffer(uv_handle_t *handle, size_t suggested_size, uv_buf_t *buf) {
buf->base = (char*) malloc(suggested_size);
buf->len = suggested_size;
}
void on_close(uv_handle_t* handle) {
free(handle);
}
void echo_write(uv_write_t *req, int status) {
if (status) {
fprintf(stderr, "Write error %s\n", uv_strerror(status));
}
free_write_req(req);
}
void echo_read(uv_stream_t *client, ssize_t nread, const uv_buf_t *buf) {
if (nread > 0) {
write_req_t *req = (write_req_t*) malloc(sizeof(write_req_t));
req->buf = uv_buf_init(buf->base, nread);
uv_write((uv_write_t*) req, client, &req->buf, 1, echo_write);
return;
}
if (nread < 0) {
if (nread != UV_EOF)
fprintf(stderr, "Read error %s\n", uv_err_name(nread));
uv_close((uv_handle_t*) client, on_close);
}
free(buf->base);
}
void on_new_connection(uv_stream_t *server, int status) {
if (status < 0) {
fprintf(stderr, "New connection error %s\n", uv_strerror(status));
// 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);
}
else {
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\n", uv_strerror(r));
return 1;
}
return uv_run(loop, UV_RUN_DEFAULT);
}
#include <stdio.h>
#include <unistd.h>
#include <uv.h>
void hare(void *arg) {
int tracklen = *((int *) arg);
while (tracklen) {
tracklen--;
sleep(1);
fprintf(stderr, "Hare ran another step\n");
}
fprintf(stderr, "Hare done running!\n");
}
void tortoise(void *arg) {
int tracklen = *((int *) arg);
while (tracklen) {
tracklen--;
fprintf(stderr, "Tortoise ran another step\n");
sleep(3);
}
fprintf(stderr, "Tortoise done running!\n");
}
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;
}
#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, "\033[2J\033[H\033[%dB\033[%luC\033[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, 1, 0);
uv_tty_set_mode(&tty, 0);
if (uv_tty_get_winsize(&tty, &width, &height)) {
fprintf(stderr, "Could not get TTY information\n");
uv_tty_reset_mode();
return 1;
}
fprintf(stderr, "Width %d, height %d\n", width, height);
uv_timer_init(loop, &tick);
uv_timer_start(&tick, update, 200, 200);
return uv_run(loop, UV_RUN_DEFAULT);
}
#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, 1, 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 = "\033[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\n";
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);
}
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <uv.h>
uv_loop_t *loop;
uv_udp_t send_socket;
uv_udp_t recv_socket;
void alloc_buffer(uv_handle_t *handle, size_t suggested_size, uv_buf_t *buf) {
buf->base = malloc(suggested_size);
buf->len = suggested_size;
}
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\n", 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\n", 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\n", ip[3], ip[2], ip[1], ip[0]);
free(buf->base);
uv_udp_recv_stop(req);
}
uv_buf_t make_discover_msg() {
uv_buf_t buffer;
alloc_buffer(NULL, 256, &buffer);
memset(buffer.base, 0, buffer.len);
// BOOTREQUEST
buffer.base[0] = 0x1;
// HTYPE ethernet
buffer.base[1] = 0x1;
// HLEN
buffer.base[2] = 0x6;
// HOPS
buffer.base[3] = 0x0;
// XID 4 bytes
buffer.base[4] = (unsigned int) random();
// SECS
buffer.base[8] = 0x0;
// FLAGS
buffer.base[10] = 0x80;
// CIADDR 12-15 is all zeros
// YIADDR 16-19 is all zeros
// SIADDR 20-23 is all zeros
// GIADDR 24-27 is all zeros
// CHADDR 28-43 is the MAC address, use your own
buffer.base[28] = 0xe4;
buffer.base[29] = 0xce;
buffer.base[30] = 0x8f;
buffer.base[31] = 0x13;
buffer.base[32] = 0xf6;
buffer.base[33] = 0xd4;
// SNAME 64 bytes zero
// FILE 128 bytes zero
// OPTIONS
// - magic cookie
buffer.base[236] = 99;
buffer.base[237] = 130;
buffer.base[238] = 83;
buffer.base[239] = 99;
// DHCP Message type
buffer.base[240] = 53;
buffer.base[241] = 1;
buffer.base[242] = 1; // DHCPDISCOVER
// DHCP Parameter request list
buffer.base[243] = 55;
buffer.base[244] = 4;
buffer.base[245] = 1;
buffer.base[246] = 3;
buffer.base[247] = 15;
buffer.base[248] = 6;
return buffer;
}
void on_send(uv_udp_send_t *req, int status) {
if (status) {
fprintf(stderr, "Send error %s\n", uv_strerror(status));
return;
}
}
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);
}
#include <assert.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <uv.h>
void on_read(uv_fs_t *req);
uv_fs_t open_req;
uv_fs_t read_req;
uv_fs_t write_req;
static char buffer[1024];
static uv_buf_t iov;
void on_write(uv_fs_t *req) {
if (req->result < 0) {
fprintf(stderr, "Write error: %s\n", uv_strerror((int)req->result));
}
else {
uv_fs_read(uv_default_loop(), &read_req, open_req.result, &iov, 1, -1, on_read);
}
}
void on_read(uv_fs_t *req) {
if (req->result < 0) {
fprintf(stderr, "Read error: %s\n", 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);
}
}
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\n", uv_strerror((int)req->result));
}
}
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;
}
#include <stdio.h>
#include <uv.h>
int64_t counter = 0;
void idle_cb(uv_idle_t *handle) {
printf("Idle callback\n");
counter++;
if (counter >= 5) {
uv_stop(uv_default_loop());
printf("uv_stop() called\n");
}
}
void prep_cb(uv_prepare_t *handle) {
printf("Prep callback\n");
}
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;
}
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <uv.h>
typedef struct {
uv_write_t req;
uv_buf_t buf;
} write_req_t;
uv_loop_t *loop;
uv_pipe_t stdin_pipe;
uv_pipe_t stdout_pipe;
uv_pipe_t file_pipe;
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 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);
}
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);
}
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;
}
#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;
typedef struct curl_context_s {
uv_poll_t poll_handle;
curl_socket_t sockfd;
} curl_context_t;
curl_context_t *create_curl_context(curl_socket_t sockfd) {
curl_context_t *context;
context = (curl_context_t*) malloc(sizeof *context);
context->sockfd = sockfd;
int r = uv_poll_init_socket(loop, &context->poll_handle, sockfd);
assert(r == 0);
context->poll_handle.data = context;
return context;
}
void curl_close_cb(uv_handle_t *handle) {
curl_context_t *context = (curl_context_t*) handle->data;
free(context);
}
void destroy_curl_context(curl_context_t *context) {
uv_close((uv_handle_t*) &context->poll_handle, curl_close_cb);
}
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\n", 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\n", url, filename);
}
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\n", done_url);
curl_multi_remove_handle(curl_handle, message->easy_handle);
curl_easy_cleanup(message->easy_handle);
break;
default:
fprintf(stderr, "CURLMSG default\n");
abort();
}
}
}
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();
}
void on_timeout(uv_timer_t *req) {
int running_handles;
curl_multi_socket_action(curl_handle, CURL_SOCKET_TIMEOUT, 0, &running_handles);
check_multi_info();
}
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'll 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;
}
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\n");
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;
}
.. _api:
API documentation
=================
.. toctree::
:maxdepth: 1
errors
version
loop
handle
request
timer
prepare
check
idle
async
poll
signal
process
stream
tcp
pipe
tty
udp
fs_event
fs_poll
fs
threadpool
dns
dll
threading
misc
# -*- coding: utf-8 -*-
#
# libuv API documentation documentation build configuration file, created by
# libuv documentation documentation build configuration file, created by
# sphinx-quickstart on Sun Jul 27 11:47:51 2014.
#
# This file is execfile()d with the current directory set to its
......@@ -64,7 +64,7 @@ master_doc = 'index'
# General information about the project.
project = u'libuv API documentation'
copyright = u'libuv contributors'
copyright = u'2014-present, libuv contributors'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
......@@ -130,10 +130,10 @@ html_theme = 'nature'
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
html_title = 'libuv API documentation'
html_title = 'libuv documentation'
# A shorter title for the navigation bar. Default is the same as html_title.
html_short_title = 'libuv %s API documentation' % version
html_short_title = 'libuv %s documentation' % version
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
......@@ -216,7 +216,7 @@ latex_elements = {
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
('index', 'libuv.tex', u'libuv API documentation',
('index', 'libuv.tex', u'libuv documentation',
u'libuv contributors', 'manual'),
]
......@@ -246,7 +246,7 @@ latex_documents = [
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'libuv', u'libuv API documentation',
('index', 'libuv', u'libuv documentation',
[u'libuv contributors'], 1)
]
......@@ -260,7 +260,7 @@ man_pages = [
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'libuv', u'libuv API documentation',
('index', 'libuv', u'libuv documentation',
u'libuv contributors', 'libuv', 'Cross-platform asynchronous I/O',
'Miscellaneous'),
]
......@@ -281,10 +281,10 @@ texinfo_documents = [
# -- Options for Epub output ----------------------------------------------
# Bibliographic Dublin Core info.
epub_title = u'libuv API documentation'
epub_title = u'libuv documentation'
epub_author = u'libuv contributors'
epub_publisher = u'libuv contributors'
epub_copyright = u'2014, libuv contributors'
epub_copyright = u'2014-present, libuv contributors'
# The basename for the epub file. It defaults to the project name.
epub_basename = u'libuv'
......
......@@ -7,7 +7,7 @@ Design overview
libuv is cross-platform support library which was originally written for NodeJS. It's designed
around the event-driven asynchronous I/O model.
The library provides much more than simply abstraction over different I/O polling mechanisms:
The library provides much more than a simple abstraction over different I/O polling mechanisms:
'handles' and 'streams' provide a high level abstraction for sockets and other entities;
cross-platform file I/O and threading functionality is also provided, amongst other things.
......@@ -25,9 +25,10 @@ Handles and requests
libuv provides users with 2 abstractions to work with, in combination with the event loop:
handles and requests.
Handles represent long-lived objects capable of performing certain operations while active. Some
examples: a prepare handle gets its callback called once every loop iteration when active, and
a TCP server handle get its connection callback called every time there is a new connection.
Handles represent long-lived objects capable of performing certain operations while active. Some examples:
- A prepare handle gets its callback called once every loop iteration when active.
- A TCP server handle that gets its connection callback called every time there is a new connection.
Requests represent (typically) short-lived operations. These operations can be performed over a
handle: write requests are used to write data on a handle; or standalone: getaddrinfo requests
......@@ -85,11 +86,11 @@ stages of a loop iteration:
* If there are no active handles or requests, the timeout is 0.
* If there are any idle handles active, the timeout is 0.
* If there are any handles pending to be closed, the timeout is 0.
* If none of the above cases was matched, the timeout of the closest timer is taken, or
* If none of the above cases matches, the timeout of the closest timer is taken, or
if there are no active timers, infinity.
#. The loop blocks for I/O. At this point the loop will block for I/O for the timeout calculated
on the previous step. All I/O related handles that were monitoring a given file descriptor
#. The loop blocks for I/O. At this point the loop will block for I/O for the duration calculated
in the previous step. All I/O related handles that were monitoring a given file descriptor
for a read or write operation get their callbacks called at this point.
#. Check handle callbacks are called. Check handles get their callbacks called right after the
......@@ -103,7 +104,7 @@ stages of a loop iteration:
so there might be timers which are due, those timers get their callbacks called.
#. Iteration ends. If the loop was run with ``UV_RUN_NOWAIT`` or ``UV_RUN_ONCE`` modes the
iteration is ended and :c:func:`uv_run` will return. If the loop was run with ``UV_RUN_DEFAULT``
iteration ends and :c:func:`uv_run` will return. If the loop was run with ``UV_RUN_DEFAULT``
it will continue from the start if it's still *alive*, otherwise it will also end.
......@@ -128,7 +129,7 @@ For a thorough explanation of the cross-platform file I/O landscape, checkout
libuv currently uses a global thread pool on which all loops can queue work on. 3 types of
operations are currently run on this pool:
* Filesystem operations
* File system operations
* DNS functions (getaddrinfo and getnameinfo)
* User specified code via :c:func:`uv_queue_work`
......
.. _fs:
Filesystem operations
=====================
File system operations
======================
libuv provides a wide variety of cross-platform sync and async filesystem
libuv provides a wide variety of cross-platform sync and async file system
operations. All functions defined in this document take a callback, which is
allowed to be NULL. If the callback is NULL the request is completed synchronously,
otherwise it will be performed asynchronously.
All file operations are run on the threadpool, see :ref:`threadpool` for information
All file operations are run on the threadpool. See :ref:`threadpool` for information
on the threadpool size.
......@@ -18,7 +18,7 @@ Data types
.. c:type:: uv_fs_t
Filesystem request type.
File system request type.
.. c:type:: uv_timespec_t
......@@ -58,7 +58,7 @@ Data types
.. c:type:: uv_fs_type
Filesystem request type.
File system request type.
::
......@@ -216,7 +216,7 @@ API
Unlike `scandir(3)`, this function does not return the "." and ".." entries.
.. note::
On Linux, getting the type of an entry is only supported by some filesystems (btrfs, ext2,
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 :man:`getdents(2)` man page.
.. c:function:: int uv_fs_stat(uv_loop_t* loop, uv_fs_t* req, const char* path, uv_fs_cb cb)
......@@ -291,7 +291,7 @@ API
Equivalent to :man:`realpath(3)` on Unix. Windows uses `GetFinalPathNameByHandle <https://msdn.microsoft.com/en-us/library/windows/desktop/aa364962(v=vs.85).aspx>`_.
.. warning::
This function has certain platform specific caveats that were discovered when used in Node.
This function has certain platform-specific caveats that were discovered when used in Node.
* macOS and other BSDs: this function will fail with UV_ELOOP if more than 32 symlinks are
found while resolving the given path. This limit is hardcoded and cannot be sidestepped.
......@@ -324,3 +324,15 @@ API
These functions are not implemented on Windows.
.. seealso:: The :c:type:`uv_req_t` API functions also apply.
Helper functions
----------------
.. c:function:: 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 <https://msdn.microsoft.com/en-us/library/ks2530z6.aspx>`_.
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.
.. versionadded:: 1.12.0
......@@ -66,7 +66,7 @@ Data types
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 filesystems such
* 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.
......@@ -74,7 +74,7 @@ Data types
UV_FS_EVENT_STAT = 2,
/*
* By default, event watcher, when watching directory, is not registering
* (is ignoring) changes in it's subdirectories.
* (is ignoring) changes in its subdirectories.
* This flag will override this behaviour on platforms that support it.
*/
UV_FS_EVENT_RECURSIVE = 4
......@@ -113,10 +113,14 @@ API
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 len will be set to the
required size.
is not big enough `UV_ENOBUFS` will be returned and `size` will be set to
the required size, including the null terminator.
.. versionchanged:: 1.3.0 the returned length no longer includes the terminating null byte,
and the buffer is not null terminated.
.. versionchanged:: 1.9.0 the returned length includes the terminating null
byte on `UV_ENOBUFS`, and the buffer is null terminated
on success.
.. seealso:: The :c:type:`uv_handle_t` API functions also apply.
......@@ -63,10 +63,15 @@ API
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 len will be set to the
required size.
is not big enough `UV_ENOBUFS` will be returned and `size` will be set to
the required size.
.. versionchanged:: 1.3.0 the returned length no longer includes the terminating null byte,
and the buffer is not null terminated.
.. versionchanged:: 1.9.0 the returned length includes the terminating null
byte on `UV_ENOBUFS`, and the buffer is null terminated
on success.
.. seealso:: The :c:type:`uv_handle_t` API functions also apply.
.. _guide:
User guide
==========
.. warning::
The contents of this guide have been recently incorporated into the libuv documentation
and it hasn't gone through thorough review yet. If you spot a mistake please file an
issue, or better yet, open a pull request!
.. toctree::
:maxdepth: 2
guide/introduction
guide/basics
guide/filesystem
guide/networking
guide/threads
guide/processes
guide/eventloops
guide/utilities
guide/about
About
=====
`Nikhil Marathe <http://nikhilism.com>`_ started writing this book one
afternoon (June 16, 2012) when he didn't feel like programming. He had recently
been stung by the lack of good documentation on libuv while working on
`node-taglib <https://github.com/nikhilm/node-taglib>`_. Although reference
documentation was present, there were no comprehensive tutorials. This book is
the output of that need and tries to be accurate. That said, the book may have
mistakes. Pull requests are encouraged.
Nikhil is indebted to Marc Lehmann's comprehensive `man page
<http://pod.tst.eu/http://cvs.schmorp.de/libev/ev.pod>`_ about libev which
describes much of the semantics of the two libraries.
This book was made using `Sphinx <http://sphinx.pocoo.org/>`_ and `vim
<http://www.vim.org>`_.
.. note::
In 2017 the libuv project incorporated the Nikhil's work into the official
documentation and it's maintained there henceforth.
Basics of libuv
===============
libuv enforces an **asynchronous**, **event-driven** style of programming. Its
core job is to provide an event loop and callback based notifications of I/O
and other activities. libuv offers core utilities like timers, non-blocking
networking support, asynchronous file system access, child processes and more.
Event loops
-----------
In event-driven programming, an application expresses interest in certain events
and respond to them when they occur. The responsibility of gathering events
from the operating system or monitoring other sources of events is handled by
libuv, and the user can register callbacks to be invoked when an event occurs.
The event-loop usually keeps running *forever*. In pseudocode:
.. code-block:: python
while there are still events to process:
e = get the next event
if there is a callback associated with e:
call the callback
Some examples of events are:
* File is ready for writing
* A socket has data ready to be read
* A timer has timed out
This event loop is encapsulated by ``uv_run()`` -- the end-all function when using
libuv.
The most common activity of systems programs is to deal with input and output,
rather than a lot of number-crunching. The problem with using conventional
input/output functions (``read``, ``fprintf``, etc.) is that they are
**blocking**. The actual write to a hard disk or reading from a network, takes
a disproportionately long time compared to the speed of the processor. The
functions don't return until the task is done, so that your program is doing
nothing. For programs which require high performance this is a major roadblock
as other activities and other I/O operations are kept waiting.
One of the standard solutions is to use threads. Each blocking I/O operation is
started in a separate thread (or in a thread pool). When the blocking function
gets invoked in the thread, the processor can schedule another thread to run,
which actually needs the CPU.
The approach followed by libuv uses another style, which is the **asynchronous,
non-blocking** style. Most modern operating systems provide event notification
subsystems. For example, a normal ``read`` call on a socket would block until
the sender actually sent something. Instead, the application can request the
operating system to watch the socket and put an event notification in the
queue. The application can inspect the events at its convenience (perhaps doing
some number crunching before to use the processor to the maximum) and grab the
data. It is **asynchronous** because the application expressed interest at one
point, then used the data at another point (in time and space). It is
**non-blocking** because the application process was free to do other tasks.
This fits in well with libuv's event-loop approach, since the operating system
events can be treated as just another libuv event. The non-blocking ensures
that other events can continue to be handled as fast as they come in [#]_.
.. NOTE::
How the I/O is run in the background is not of our concern, but due to the
way our computer hardware works, with the thread as the basic unit of the
processor, libuv and OSes will usually run background/worker threads and/or
polling to perform tasks in a non-blocking manner.
Bert Belder, one of the libuv core developers has a small video explaining the
architecture of libuv and its background. If you have no prior experience with
either libuv or libev, it is a quick, useful watch.
libuv's event loop is explained in more detail in the `documentation
<http://docs.libuv.org/en/v1.x/design.html#the-i-o-loop>`_.
.. raw:: html
<iframe width="560" height="315"
src="https://www.youtube-nocookie.com/embed/nGn60vDSxQ4" frameborder="0"
allowfullscreen></iframe>
Hello World
-----------
With the basics out of the way, lets write our first libuv program. It does
nothing, except start a loop which will exit immediately.
.. rubric:: helloworld/main.c
.. literalinclude:: ../code/helloworld/main.c
:linenos:
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.
Default loop
++++++++++++
A default loop is provided by libuv and can be accessed using
``uv_default_loop()``. You should use this loop if you only want a single
loop.
.. note::
node.js uses the default loop as its main loop. If you are writing bindings
you should be aware of this.
.. _libuv-error-handling:
Error handling
--------------
Initialization functions or synchronous functions which may fail return a negative number on error. Async functions that may fail will pass a status parameter to their callbacks. The error messages are defined as ``UV_E*`` `constants`_.
.. _constants: http://docs.libuv.org/en/v1.x/errors.html#error-constants
You can use the ``uv_strerror(int)`` and ``uv_err_name(int)`` functions
to get a ``const char *`` describing the error or the error name respectively.
I/O read callbacks (such as for files and sockets) are passed a parameter ``nread``. If ``nread`` is less than 0, there was an error (UV_EOF is the end of file error, which you may want to handle differently).
Handles and Requests
--------------------
libuv works by the user expressing interest in particular events. This is
usually done by creating a **handle** to an I/O device, timer or process.
Handles are opaque structs named as ``uv_TYPE_t`` where type signifies what the
handle is used for.
.. rubric:: libuv watchers
.. literalinclude:: ../libuv/include/uv.h
:lines: 197-230
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::
uv_TYPE_init(uv_loop_t *, uv_TYPE_t *)
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's callback will receive
the data read from a file, a timer callback will be triggered on timeout and so
on.
Idling
++++++
Here is an example of using an idle handle. The callback is called once on
every turn of the event loop. A use case for idle handles is discussed in
:doc:`utilities`. Let us use an idle watcher to look at the watcher life cycle
and see how ``uv_run()`` will now block because a watcher is present. The idle
watcher is stopped when the count is reached and ``uv_run()`` exits since no
event watchers are active.
.. rubric:: idle-basic/main.c
.. literalinclude:: ../code/idle-basic/main.c
:emphasize-lines: 6,10,14-17
Storing context
+++++++++++++++
In callback based programming style you'll often want to pass some 'context' --
application specific information -- between the call site and the callback. All
handles and requests have a ``void* data`` member which you can set to the
context and cast back in the callback. This is a common pattern used throughout
the C library ecosystem. In addition ``uv_loop_t`` also has a similar data
member.
----
.. [#] Depending on the capacity of the hardware of course.
Advanced event loops
====================
libuv provides considerable user control over event loops, and you can achieve
interesting results by juggling multiple loops. You can also embed libuv's
event loop into another event loop based library -- imagine a Qt based UI, and
Qt's event loop driving a libuv backend which does intensive system level
tasks.
Stopping an event loop
~~~~~~~~~~~~~~~~~~~~~~
``uv_stop()`` can be used to stop an event loop. The earliest the loop will
stop running is *on the next iteration*, possibly later. This means that events
that are ready to be processed in this iteration of the loop will still be
processed, so ``uv_stop()`` can't be used as a kill switch. When ``uv_stop()``
is called, the loop **won't** block for i/o on this iteration. The semantics of
these things can be a bit difficult to understand, so let's look at
``uv_run()`` where all the control flow occurs.
.. rubric:: src/unix/core.c - uv_run
.. literalinclude:: ../libuv/src/unix/core.c
:linenos:
:lines: 304-324
:emphasize-lines: 10,19,21
``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.
.. rubric:: uvstop/main.c
.. literalinclude:: ../code/uvstop/main.c
:linenos:
:emphasize-lines: 11
Introduction
============
This 'book' is a small set of tutorials about using libuv_ as
a high performance evented I/O library which offers the same API on Windows and Unix.
It is meant to cover the main areas of libuv, but is not a comprehensive
reference discussing every function and data structure. The `official libuv
documentation`_ may be consulted for full details.
.. _official libuv documentation: http://docs.libuv.org/en/v1.x/
This book is still a work in progress, so sections may be incomplete, but
I hope you will enjoy it as it grows.
Who this book is for
--------------------
If you are reading this book, you are either:
1) a systems programmer, creating low-level programs such as daemons or network
services and clients. You have found that the event loop approach is well
suited for your application and decided to use libuv.
2) a node.js module writer, who wants to wrap platform APIs
written in C or C++ with a set of (a)synchronous APIs that are exposed to
JavaScript. You will use libuv purely in the context of node.js. For
this you will require some other resources as the book does not cover parts
specific to v8/node.js.
This book assumes that you are comfortable with the C programming language.
Background
----------
The node.js_ project began in 2009 as a JavaScript environment decoupled
from the browser. Using Google's V8_ and Marc Lehmann's libev_, node.js
combined a model of I/O -- evented -- with a language that was well suited to
the style of programming; due to the way it had been shaped by browsers. As
node.js grew in popularity, it was important to make it work on Windows, but
libev ran only on Unix. The Windows equivalent of kernel event notification
mechanisms like kqueue or (e)poll is IOCP. libuv was an abstraction around libev
or IOCP depending on the platform, providing users an API based on libev.
In the node-v0.9.0 version of libuv `libev was removed`_.
Since then libuv has continued to mature and become a high quality standalone
library for system programming. Users outside of node.js include Mozilla's
Rust_ programming language, and a variety_ of language bindings.
This book and the code is based on libuv version `v1.3.0`_.
Code
----
All the code from this book is included as part of the source of the book on
Github. `Clone`_/`Download`_ the book, then build libuv::
cd libuv
./autogen.sh
./configure
make
There is no need to ``make install``. To build the examples run ``make`` in the
``code/`` directory.
.. _Clone: https://github.com/nikhilm/uvbook
.. _Download: https://github.com/nikhilm/uvbook/downloads
.. _v1.3.0: https://github.com/libuv/libuv/tags
.. _V8: http://code.google.com/p/v8/
.. _libev: http://software.schmorp.de/pkg/libev.html
.. _libuv: https://github.com/libuv/libuv
.. _node.js: http://www.nodejs.org
.. _libev was removed: https://github.com/joyent/libuv/issues/485
.. _Rust: http://rust-lang.org
.. _variety: https://github.com/libuv/libuv/wiki/Projects-that-use-libuv
Networking
==========
Networking in libuv is not much different from directly using the BSD socket
interface, some things are easier, all are non-blocking, but the concepts stay
the same. In addition libuv offers utility functions to abstract the annoying,
repetitive and low-level tasks like setting up sockets using the BSD socket
structures, DNS lookup, and tweaking various socket parameters.
The ``uv_tcp_t`` and ``uv_udp_t`` structures are used for network I/O.
.. NOTE::
The code samples in this chapter exist to show certain libuv APIs. They are
not examples of good quality code. They leak memory and don't always close
connections properly.
TCP
---
TCP is a connection oriented, stream protocol and is therefore based on the
libuv streams infrastructure.
Server
++++++
Server sockets proceed by:
1. ``uv_tcp_init`` the TCP handle.
2. ``uv_tcp_bind`` it.
3. Call ``uv_listen`` on the handle to have a callback invoked whenever a new
connection is established by a client.
4. Use ``uv_accept`` to accept the connection.
5. Use :ref:`stream operations <buffers-and-streams>` to communicate with the
client.
Here is a simple echo server
.. rubric:: tcp-echo-server/main.c - The listen socket
.. literalinclude:: ../code/tcp-echo-server/main.c
:linenos:
:lines: 68-
:emphasize-lines: 4-5,7-10
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::
There are ``uv_ip6_*`` analogues for the ip4 functions.
Most of the setup functions are synchronous since they are CPU-bound.
``uv_listen`` is where we return to libuv's 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.
.. rubric:: tcp-echo-server/main.c - Accepting the client
.. literalinclude:: ../code/tcp-echo-server/main.c
:linenos:
:lines: 51-66
:emphasize-lines: 9-10
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't
required. This can be done even in the ``uv_listen`` callback if you are not
interested in accepting the connection.
Client
++++++
Where you do bind/listen/accept on the server, on the client side it's simply
a matter of calling ``uv_tcp_connect``. The same ``uv_connect_cb`` style
callback of ``uv_listen`` is used by ``uv_tcp_connect``. Try::
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);
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.
UDP
---
The `User Datagram Protocol`_ offers connectionless, unreliable network
communication. Hence libuv doesn't offer a stream. Instead libuv provides
non-blocking UDP support via the `uv_udp_t` handle (for receiving) and
`uv_udp_send_t` request (for sending) and related functions. That said, the
actual API for reading/writing is very similar to normal stream reads. To look
at how UDP can be used, the example shows the first stage of obtaining an IP
address from a `DHCP`_ server -- DHCP Discover.
.. note::
You will have to run `udp-dhcp` as **root** since it uses well known port
numbers below 1024.
.. rubric:: udp-dhcp/main.c - Setup and send UDP packets
.. literalinclude:: ../code/udp-dhcp/main.c
:linenos:
:lines: 7-11,104-
:emphasize-lines: 8,10-11,17-18,21
.. note::
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.
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 [#]_. 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't 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's UDP for you!).
.. rubric:: udp-dhcp/main.c - Reading packets
.. literalinclude:: ../code/udp-dhcp/main.c
:linenos:
:lines: 17-40
:emphasize-lines: 1,23
UDP Options
+++++++++++
Time-to-live
~~~~~~~~~~~~
The TTL of packets sent on the socket can be changed using ``uv_udp_set_ttl``.
IPv6 stack only
~~~~~~~~~~~~~~~
IPv6 sockets can be used for both IPv4 and IPv6 communication. If you want to
restrict the socket to IPv6 only, pass the ``UV_UDP_IPV6ONLY`` flag to
``uv_udp_bind`` [#]_.
Multicast
~~~~~~~~~
A socket can (un)subscribe to a multicast group using:
.. literalinclude:: ../libuv/include/uv.h
:lines: 594-597
where ``membership`` is ``UV_JOIN_GROUP`` or ``UV_LEAVE_GROUP``.
The concepts of multicasting are nicely explained in `this guide`_.
.. _this guide: http://www.tldp.org/HOWTO/Multicast-HOWTO-2.html
Local loopback of multicast packets is enabled by default [#]_, use
``uv_udp_set_multicast_loop`` to switch it off.
The packet time-to-live for multicast packets can be changed using
``uv_udp_set_multicast_ttl``.
Querying DNS
------------
libuv provides asynchronous DNS resolution. For this it provides its own
``getaddrinfo`` replacement [#]_. In the callback you can
perform normal socket operations on the retrieved addresses. Let's connect to
Freenode to see an example of DNS resolution.
.. rubric:: dns/main.c
.. literalinclude:: ../code/dns/main.c
:linenos:
:lines: 61-
:emphasize-lines: 12
If ``uv_getaddrinfo`` returns non-zero, something went wrong in the setup and
your callback won't 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 <getaddrinfo>`_. 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.
.. rubric:: dns/main.c
.. literalinclude:: ../code/dns/main.c
:linenos:
:lines: 42-60
:emphasize-lines: 8,16
libuv also provides the inverse `uv_getnameinfo`_.
.. _uv_getnameinfo: http://docs.libuv.org/en/v1.x/dns.html#c.uv_getnameinfo
Network interfaces
------------------
Information about the system's network interfaces can be obtained through libuv
using ``uv_interface_addresses``. This simple program just prints out all the
interface details so you get an idea of the fields that are available. This is
useful to allow your service to bind to IP addresses when it starts.
.. rubric:: interfaces/main.c
.. literalinclude:: ../code/interfaces/main.c
:linenos:
:emphasize-lines: 9,17
``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.
.. _c-ares: http://c-ares.haxx.se
.. _getaddrinfo: http://www.kernel.org/doc/man-pages/online/pages/man3/getaddrinfo.3.html
.. _User Datagram Protocol: http://en.wikipedia.org/wiki/User_Datagram_Protocol
.. _DHCP: http://tools.ietf.org/html/rfc2131
----
.. [#] http://beej.us/guide/bgnet/output/html/multipage/advanced.html#broadcast
.. [#] on Windows only supported on Windows Vista and later.
.. [#] http://www.tldp.org/HOWTO/Multicast-HOWTO-6.html#ss6.1
.. [#] libuv use the system ``getaddrinfo`` in the libuv threadpool. libuv
v0.8.0 and earlier also included c-ares_ as an alternative, but this has been
removed in v0.9.0.
差异被折叠。
差异被折叠。
差异被折叠。
......@@ -86,9 +86,9 @@ Public members
Pointer to the :c:type:`uv_loop_t` where the handle is running on. Readonly.
.. c:member:: uv_loop_t* uv_handle_t.type
.. c:member:: uv_handle_type uv_handle_t.type
Pointer to the :c:type:`uv_handle_type`. Readonly.
The :c:type:`uv_handle_type`, indicating the type of the underlying handle. Readonly.
.. c:member:: void* uv_handle_t.data
......
Welcome to the libuv API documentation
======================================
Welcome to the libuv documentation
==================================
Overview
--------
......@@ -37,59 +37,26 @@ Features
* Threading and synchronization primitives
Downloads
---------
libuv can be downloaded from `here <http://dist.libuv.org/dist/>`_.
Documentation
-------------
Installation
------------
.. toctree::
:maxdepth: 1
Installation instructions can be found on `the README <https://github.com/libuv/libuv/blob/master/README.md>`_.
design
api
guide
upgrading
Upgrading
Downloads
---------
Migration guides for different libuv versions, starting with 1.0.
.. toctree::
:maxdepth: 1
migration_010_100
libuv can be downloaded from `here <http://dist.libuv.org/dist/>`_.
Documentation
-------------
Installation
------------
.. toctree::
:maxdepth: 1
Installation instructions can be found in `the README <https://github.com/libuv/libuv/blob/master/README.md>`_.
design
errors
version
loop
handle
request
timer
prepare
check
idle
async
poll
signal
process
stream
tcp
pipe
tty
udp
fs_event
fs_poll
fs
threadpool
dns
dll
threading
misc
......@@ -38,9 +38,8 @@ Public members
.. c:member:: void* uv_loop_t.data
Space for user-defined arbitrary data. libuv does not use this field. libuv does, however,
initialize it to NULL in :c:func:`uv_loop_init`, and it poisons the value (on debug builds)
on :c:func:`uv_loop_close`.
Space for user-defined arbitrary data. libuv does not use and does not
touch this field.
API
......@@ -165,3 +164,57 @@ API
.. c:function:: 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`.
.. c:function:: int uv_loop_fork(uv_loop_t* loop)
.. versionadded:: 1.12.0
Reinitialize any kernel state necessary in the child process after
a :man:`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't
continue to use it in the parent). This function must be called
before calling :c:func:`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::
This function is experimental. It may contain bugs, and is subject to
change or removal. API and ABI stability is not guaranteed.
.. note::
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.
.. caution::
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.
.. caution::
Any previous value returned from :c:func`uv_backend_fd` is now
invalid. That function must be called again to determine the
correct backend file descriptor.
......@@ -270,12 +270,20 @@ API
.. c:function:: int uv_cwd(char* buffer, size_t* size)
Gets the current working directory.
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.
.. versionchanged:: 1.1.0
On Unix the path no longer ends in a slash.
.. versionchanged:: 1.9.0 the returned length includes the terminating null
byte on `UV_ENOBUFS`, and the buffer is null terminated
on success.
.. c:function:: int uv_chdir(const char* dir)
Changes the current working directory.
......@@ -386,3 +394,49 @@ API
stability guarantees.
.. versionadded:: 1.8.0
.. c:function:: 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::
This function is not thread safe.
.. versionadded:: 1.12.0
.. c:function:: int uv_os_setenv(const char* name, const char* value)
Creates or updates the environment variable specified by `name` with
`value`.
.. warning::
This function is not thread safe.
.. versionadded:: 1.12.0
.. c:function:: 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::
This function is not thread safe.
.. versionadded:: 1.12.0
.. c:function:: 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.
.. versionadded:: 1.12.0
......@@ -70,6 +70,13 @@ API
Start the handle with the given callback, watching for the given signal.
.. c:function:: int uv_signal_start_oneshot(uv_signal_t* signal, uv_signal_cb cb, int signum)
.. versionadded:: 1.12.0
Same functionality as :c:func:`uv_signal_start` but the signal handler is reset the moment
the signal is received.
.. c:function:: int uv_signal_stop(uv_signal_t* signal)
Stop the handle, the callback will no longer be called.
......
......@@ -5,7 +5,7 @@ Thread pool work scheduling
===========================
libuv provides a threadpool which can be used to run user code and get notified
in the loop thread. This thread pool is internally used to run all filesystem
in the loop thread. This thread pool is internally used to run all file system
operations, as well as getaddrinfo and getnameinfo requests.
Its default size is 4, but it can be changed at startup time by setting the
......
.. _upgrading:
Upgrading
=========
Migration guides for different libuv versions, starting with 1.0.
.. toctree::
:maxdepth: 1
migration_010_100
/* Copyright libuv project contributors. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#ifndef UV_POSIX_H
#define UV_POSIX_H
#define UV_PLATFORM_LOOP_FIELDS \
struct pollfd* poll_fds; \
size_t poll_fds_used; \
size_t poll_fds_size; \
unsigned char poll_fds_iterating; \
#endif /* UV_POSIX_H */
......@@ -60,6 +60,8 @@
defined(__OpenBSD__) || \
defined(__NetBSD__)
# include "uv-bsd.h"
#elif defined(__CYGWIN__) || defined(__MSYS__)
# include "uv-posix.h"
#endif
#ifndef PTHREAD_BARRIER_SERIAL_THREAD
......@@ -79,7 +81,6 @@
#endif
struct uv__io_s;
struct uv__async;
struct uv_loop_s;
typedef void (*uv__io_cb)(struct uv_loop_s* loop,
......@@ -97,16 +98,6 @@ struct uv__io_s {
UV_IO_PRIVATE_PLATFORM_FIELDS
};
typedef void (*uv__async_cb)(struct uv_loop_s* loop,
struct uv__async* w,
unsigned int nevents);
struct uv__async {
uv__async_cb cb;
uv__io_t io_watcher;
int wfd;
};
#ifndef UV_PLATFORM_SEM_T
# define UV_PLATFORM_SEM_T sem_t
#endif
......@@ -216,7 +207,9 @@ typedef struct {
void* check_handles[2]; \
void* idle_handles[2]; \
void* async_handles[2]; \
struct uv__async async_watcher; \
void (*async_unused)(void); /* TODO(bnoordhuis) Remove in libuv v2. */ \
uv__io_t async_io_watcher; \
int async_wfd; \
struct { \
void* min; \
unsigned int nelts; \
......
......@@ -31,7 +31,7 @@
*/
#define UV_VERSION_MAJOR 1
#define UV_VERSION_MINOR 11
#define UV_VERSION_MINOR 12
#define UV_VERSION_PATCH 0
#define UV_VERSION_IS_RELEASE 1
#define UV_VERSION_SUFFIX ""
......
......@@ -274,6 +274,7 @@ UV_EXTERN void uv_loop_delete(uv_loop_t*);
UV_EXTERN size_t uv_loop_size(void);
UV_EXTERN int uv_loop_alive(const uv_loop_t* loop);
UV_EXTERN int uv_loop_configure(uv_loop_t* loop, uv_loop_option option, ...);
UV_EXTERN int uv_loop_fork(uv_loop_t* loop);
UV_EXTERN int uv_run(uv_loop_t*, uv_run_mode mode);
UV_EXTERN void uv_stop(uv_loop_t*);
......@@ -1033,6 +1034,7 @@ UV_EXTERN int uv_get_process_title(char* buffer, size_t size);
UV_EXTERN int uv_set_process_title(const char* title);
UV_EXTERN int uv_resident_set_memory(size_t* rss);
UV_EXTERN int uv_uptime(double* uptime);
UV_EXTERN uv_os_fd_t uv_get_osfhandle(int fd);
typedef struct {
long tv_sec;
......@@ -1073,6 +1075,12 @@ UV_EXTERN int uv_interface_addresses(uv_interface_address_t** addresses,
UV_EXTERN void uv_free_interface_addresses(uv_interface_address_t* addresses,
int count);
UV_EXTERN int uv_os_getenv(const char* name, char* buffer, size_t* size);
UV_EXTERN int uv_os_setenv(const char* name, const char* value);
UV_EXTERN int uv_os_unsetenv(const char* name);
UV_EXTERN int uv_os_gethostname(char* buffer, size_t* size);
typedef enum {
UV_FS_UNKNOWN = -1,
......@@ -1324,6 +1332,9 @@ UV_EXTERN int uv_signal_init(uv_loop_t* loop, uv_signal_t* handle);
UV_EXTERN int uv_signal_start(uv_signal_t* handle,
uv_signal_cb signal_cb,
int signum);
UV_EXTERN int uv_signal_start_oneshot(uv_signal_t* handle,
uv_signal_cb signal_cb,
int signum);
UV_EXTERN int uv_signal_stop(uv_signal_t* handle);
UV_EXTERN void uv_loadavg(double avg[3]);
......
......@@ -95,7 +95,7 @@ static int do_kill(client_ctx *cx);
static int do_almost_dead(client_ctx *cx);
static int conn_cycle(const char *who, conn *a, conn *b);
static void conn_timer_reset(conn *c);
static void conn_timer_expire(uv_timer_t *handle, int status);
static void conn_timer_expire(uv_timer_t *handle);
static void conn_getaddrinfo(conn *c, const char *hostname);
static void conn_getaddrinfo_done(uv_getaddrinfo_t *req,
int status,
......@@ -582,10 +582,9 @@ static void conn_timer_reset(conn *c) {
0));
}
static void conn_timer_expire(uv_timer_t *handle, int status) {
static void conn_timer_expire(uv_timer_t *handle) {
conn *c;
CHECK(0 == status);
c = CONTAINER_OF(handle, conn, timer_handle);
c->result = UV_ETIMEDOUT;
do_next(c->client);
......
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
Markdown 格式
0% 或
您添加了 0 人 到此讨论。请谨慎行事。
请先完成此评论的编辑!
请 注册 或者 后发表评论