├── .gitignore ├── README.md ├── code ├── cgi │ ├── main.c │ └── tick.c ├── detach │ └── main.c ├── dns │ └── main.c ├── helloworld │ └── main.c ├── idle-basic │ └── main.c ├── idle-compute │ └── main.c ├── interfaces │ └── main.c ├── locks │ └── main.c ├── multi-echo-server │ ├── hammer.js │ ├── main.c │ └── worker.c ├── onchange │ └── main.c ├── pipe-echo-server │ └── main.c ├── plugin │ ├── hello.c │ ├── main.c │ └── plugin.h ├── proc-streams │ ├── main.c │ └── test.c ├── progress │ └── main.c ├── queue-cancel │ └── main.c ├── queue-work │ └── main.c ├── ref-timer │ └── main.c ├── signal │ └── main.c ├── spawn │ └── main.c ├── tcp-echo-server │ └── main.c ├── thread-create │ └── main.c ├── tty-gravity │ └── main.c ├── tty │ └── main.c ├── udp-dhcp │ └── main.c ├── uvcat │ └── main.c ├── uvstop │ └── main.c ├── uvtee │ └── main.c └── uvwget │ └── main.c └── source ├── about.md ├── advanced-event-loops.md ├── basics_of_libuv.md ├── filesystem.md ├── introduction.md ├── networking.md ├── processes.md ├── threads.md └── utilities.md /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | source/.DS_Store 3 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # libuv中文教程 2 | 翻译自[《An Introduction to libuv》](https://github.com/nikhilm/uvbook). 3 | 会持续关注原教程并更新中文版,本教程基于libuv的v1.3.0。 4 | 5 | ## 在线阅读 6 | 目前关闭gitbook在线阅读,大家直接在github上查看md文件即可。 7 | 8 | ## 目录 9 | 1. [简介](./source/introduction.md) 10 | 2. [libuv基础](./source/basics_of_libuv.md) 11 | 3. [文件系统](./source/filesystem.md) 12 | 4. [网络](./source/networking.md) 13 | 5. [线程](./source/threads.md) 14 | 6. [进程](./source/processes.md) 15 | 7. [高级事件循环](./source/advanced-event-loops.md) 16 | 8. [实用工具](./source/utilities.md) 17 | 9. [关于](./source/about.md) 18 | 19 | ## 翻译人员 20 | 翻译人员[在这](https://github.com/luohaha/Chinese-uvbook/graphs/contributors)。 21 | 22 | ## 辅助阅读 23 | 1. [libuv官方文档](http://docs.libuv.org/en/v1.x/)-由于教程有些知识点讲解得不够深入,需要我们自行阅读官方文档,来加强理解。 24 | 2. [教程的完整代码](https://github.com/nikhilm/uvbook/tree/master/code)-教程中展示的代码并不完整,对于一些复杂的程序,需要阅读完整的实例代码。 25 | 26 | ## 说明 27 | 在翻译的过程中,对于一些个人觉得可能不是那么容易理解的知识点,我都会附上自己收集的说明资料的链接,以方便学习。由于个人的英文水平有限,如果大家发现翻译出错或者不合适的地方,欢迎PR(修改master分支下,source文件夹下的md文件即可)。 28 | 29 | -------------------------------------------------------------------------------- /code/cgi/main.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | uv_loop_t *loop; 8 | uv_process_t child_req; 9 | uv_process_options_t options; 10 | 11 | void cleanup_handles(uv_process_t *req, int64_t exit_status, int term_signal) { 12 | fprintf(stderr, "Process exited with status %" PRId64 ", signal %d\n", exit_status, term_signal); 13 | uv_close((uv_handle_t*) req->data, NULL); 14 | uv_close((uv_handle_t*) req, NULL); 15 | } 16 | 17 | void invoke_cgi_script(uv_tcp_t *client) { 18 | size_t size = 500; 19 | char path[size]; 20 | uv_exepath(path, &size); 21 | strcpy(path + (strlen(path) - strlen("cgi")), "tick"); 22 | 23 | char* args[2]; 24 | args[0] = path; 25 | args[1] = NULL; 26 | 27 | /* ... finding the executable path and setting up arguments ... */ 28 | 29 | options.stdio_count = 3; 30 | uv_stdio_container_t child_stdio[3]; 31 | child_stdio[0].flags = UV_IGNORE; 32 | child_stdio[1].flags = UV_INHERIT_STREAM; 33 | child_stdio[1].data.stream = (uv_stream_t*) client; 34 | child_stdio[2].flags = UV_IGNORE; 35 | options.stdio = child_stdio; 36 | 37 | options.exit_cb = cleanup_handles; 38 | options.file = args[0]; 39 | options.args = args; 40 | 41 | // Set this so we can close the socket after the child process exits. 42 | child_req.data = (void*) client; 43 | int r; 44 | if ((r = uv_spawn(loop, &child_req, &options))) { 45 | fprintf(stderr, "%s\n", uv_strerror(r)); 46 | return; 47 | } 48 | } 49 | 50 | void on_new_connection(uv_stream_t *server, int status) { 51 | if (status == -1) { 52 | // error! 53 | return; 54 | } 55 | 56 | uv_tcp_t *client = (uv_tcp_t*) malloc(sizeof(uv_tcp_t)); 57 | uv_tcp_init(loop, client); 58 | if (uv_accept(server, (uv_stream_t*) client) == 0) { 59 | invoke_cgi_script(client); 60 | } 61 | else { 62 | uv_close((uv_handle_t*) client, NULL); 63 | } 64 | } 65 | 66 | int main() { 67 | loop = uv_default_loop(); 68 | 69 | uv_tcp_t server; 70 | uv_tcp_init(loop, &server); 71 | 72 | struct sockaddr_in bind_addr; 73 | uv_ip4_addr("0.0.0.0", 7000, &bind_addr); 74 | uv_tcp_bind(&server, (const struct sockaddr *)&bind_addr, 0); 75 | int r = uv_listen((uv_stream_t*) &server, 128, on_new_connection); 76 | if (r) { 77 | fprintf(stderr, "Listen error %s\n", uv_err_name(r)); 78 | return 1; 79 | } 80 | return uv_run(loop, UV_RUN_DEFAULT); 81 | } 82 | -------------------------------------------------------------------------------- /code/cgi/tick.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() { 5 | int i; 6 | for (i = 0; i < 10; i++) { 7 | printf("tick\n"); 8 | fflush(stdout); 9 | sleep(1); 10 | } 11 | printf("BOOM!\n"); 12 | return 0; 13 | } 14 | -------------------------------------------------------------------------------- /code/detach/main.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include 4 | 5 | uv_loop_t *loop; 6 | uv_process_t child_req; 7 | uv_process_options_t options; 8 | 9 | int main() { 10 | loop = uv_default_loop(); 11 | 12 | char* args[3]; 13 | args[0] = "sleep"; 14 | args[1] = "100"; 15 | args[2] = NULL; 16 | 17 | options.exit_cb = NULL; 18 | options.file = "sleep"; 19 | options.args = args; 20 | options.flags = UV_PROCESS_DETACHED; 21 | 22 | int r; 23 | if ((r = uv_spawn(loop, &child_req, &options))) { 24 | fprintf(stderr, "%s\n", uv_strerror(r)); 25 | return 1; 26 | } 27 | fprintf(stderr, "Launched sleep with PID %d\n", child_req.pid); 28 | uv_unref((uv_handle_t*) &child_req); 29 | 30 | return uv_run(loop, UV_RUN_DEFAULT); 31 | } 32 | -------------------------------------------------------------------------------- /code/dns/main.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | uv_loop_t *loop; 7 | 8 | void alloc_buffer(uv_handle_t *handle, size_t suggested_size, uv_buf_t *buf) { 9 | buf->base = malloc(suggested_size); 10 | buf->len = suggested_size; 11 | } 12 | 13 | void on_read(uv_stream_t *client, ssize_t nread, const uv_buf_t *buf) { 14 | if (nread < 0) { 15 | if (nread != UV_EOF) 16 | fprintf(stderr, "Read error %s\n", uv_err_name(nread)); 17 | uv_close((uv_handle_t*) client, NULL); 18 | free(buf->base); 19 | free(client); 20 | return; 21 | } 22 | 23 | char *data = (char*) malloc(sizeof(char) * (nread+1)); 24 | data[nread] = '\0'; 25 | strncpy(data, buf->base, nread); 26 | 27 | fprintf(stderr, "%s", data); 28 | free(data); 29 | free(buf->base); 30 | } 31 | 32 | void on_connect(uv_connect_t *req, int status) { 33 | if (status < 0) { 34 | fprintf(stderr, "connect failed error %s\n", uv_err_name(status)); 35 | free(req); 36 | return; 37 | } 38 | 39 | uv_read_start((uv_stream_t*) req->handle, alloc_buffer, on_read); 40 | free(req); 41 | } 42 | 43 | void on_resolved(uv_getaddrinfo_t *resolver, int status, struct addrinfo *res) { 44 | if (status < 0) { 45 | fprintf(stderr, "getaddrinfo callback error %s\n", uv_err_name(status)); 46 | return; 47 | } 48 | 49 | char addr[17] = {'\0'}; 50 | uv_ip4_name((struct sockaddr_in*) res->ai_addr, addr, 16); 51 | fprintf(stderr, "%s\n", addr); 52 | 53 | uv_connect_t *connect_req = (uv_connect_t*) malloc(sizeof(uv_connect_t)); 54 | uv_tcp_t *socket = (uv_tcp_t*) malloc(sizeof(uv_tcp_t)); 55 | uv_tcp_init(loop, socket); 56 | 57 | uv_tcp_connect(connect_req, socket, (const struct sockaddr*) res->ai_addr, on_connect); 58 | 59 | uv_freeaddrinfo(res); 60 | } 61 | 62 | int main() { 63 | loop = uv_default_loop(); 64 | 65 | struct addrinfo hints; 66 | hints.ai_family = PF_INET; 67 | hints.ai_socktype = SOCK_STREAM; 68 | hints.ai_protocol = IPPROTO_TCP; 69 | hints.ai_flags = 0; 70 | 71 | uv_getaddrinfo_t resolver; 72 | fprintf(stderr, "irc.libera.chat is... "); 73 | int r = uv_getaddrinfo(loop, &resolver, on_resolved, "irc.libera.chat", "6667", &hints); 74 | 75 | if (r) { 76 | fprintf(stderr, "getaddrinfo call error %s\n", uv_err_name(r)); 77 | return 1; 78 | } 79 | return uv_run(loop, UV_RUN_DEFAULT); 80 | } 81 | -------------------------------------------------------------------------------- /code/helloworld/main.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int main() { 6 | uv_loop_t *loop = malloc(sizeof(uv_loop_t)); 7 | uv_loop_init(loop); 8 | 9 | printf("Now quitting.\n"); 10 | uv_run(loop, UV_RUN_DEFAULT); 11 | 12 | uv_loop_close(loop); 13 | free(loop); 14 | return 0; 15 | } 16 | -------------------------------------------------------------------------------- /code/idle-basic/main.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int64_t counter = 0; 5 | 6 | void wait_for_a_while(uv_idle_t* handle) { 7 | counter++; 8 | 9 | if (counter >= 10e6) 10 | uv_idle_stop(handle); 11 | } 12 | 13 | int main() { 14 | uv_idle_t idler; 15 | 16 | uv_idle_init(uv_default_loop(), &idler); 17 | uv_idle_start(&idler, wait_for_a_while); 18 | 19 | printf("Idling...\n"); 20 | uv_run(uv_default_loop(), UV_RUN_DEFAULT); 21 | 22 | uv_loop_close(uv_default_loop()); 23 | return 0; 24 | } 25 | -------------------------------------------------------------------------------- /code/idle-compute/main.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include 4 | 5 | uv_loop_t *loop; 6 | uv_fs_t stdin_watcher; 7 | uv_idle_t idler; 8 | char buffer[1024]; 9 | 10 | void crunch_away(uv_idle_t* handle) { 11 | // Compute extra-terrestrial life 12 | // fold proteins 13 | // computer another digit of PI 14 | // or similar 15 | fprintf(stderr, "Computing PI...\n"); 16 | // just to avoid overwhelming your terminal emulator 17 | uv_idle_stop(handle); 18 | } 19 | 20 | void on_type(uv_fs_t *req) { 21 | if (stdin_watcher.result > 0) { 22 | buffer[stdin_watcher.result] = '\0'; 23 | printf("Typed %s\n", buffer); 24 | 25 | uv_buf_t buf = uv_buf_init(buffer, 1024); 26 | uv_fs_read(loop, &stdin_watcher, 0, &buf, 1, -1, on_type); 27 | uv_idle_start(&idler, crunch_away); 28 | } 29 | else if (stdin_watcher.result < 0) { 30 | fprintf(stderr, "error opening file: %s\n", uv_strerror(req->result)); 31 | } 32 | } 33 | 34 | int main() { 35 | loop = uv_default_loop(); 36 | 37 | uv_idle_init(loop, &idler); 38 | 39 | uv_buf_t buf = uv_buf_init(buffer, 1024); 40 | uv_fs_read(loop, &stdin_watcher, 0, &buf, 1, -1, on_type); 41 | uv_idle_start(&idler, crunch_away); 42 | return uv_run(loop, UV_RUN_DEFAULT); 43 | } 44 | -------------------------------------------------------------------------------- /code/interfaces/main.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() { 5 | char buf[512]; 6 | uv_interface_address_t *info; 7 | int count, i; 8 | 9 | uv_interface_addresses(&info, &count); 10 | i = count; 11 | 12 | printf("Number of interfaces: %d\n", count); 13 | while (i--) { 14 | uv_interface_address_t interface = info[i]; 15 | 16 | printf("Name: %s\n", interface.name); 17 | printf("Internal? %s\n", interface.is_internal ? "Yes" : "No"); 18 | 19 | if (interface.address.address4.sin_family == AF_INET) { 20 | uv_ip4_name(&interface.address.address4, buf, sizeof(buf)); 21 | printf("IPv4 address: %s\n", buf); 22 | } 23 | else if (interface.address.address4.sin_family == AF_INET6) { 24 | uv_ip6_name(&interface.address.address6, buf, sizeof(buf)); 25 | printf("IPv6 address: %s\n", buf); 26 | } 27 | 28 | printf("\n"); 29 | } 30 | 31 | uv_free_interface_addresses(info, count); 32 | return 0; 33 | } 34 | -------------------------------------------------------------------------------- /code/locks/main.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | uv_barrier_t blocker; 5 | uv_rwlock_t numlock; 6 | int shared_num; 7 | 8 | void reader(void *n) 9 | { 10 | int num = *(int *)n; 11 | int i; 12 | for (i = 0; i < 20; i++) { 13 | uv_rwlock_rdlock(&numlock); 14 | printf("Reader %d: acquired lock\n", num); 15 | printf("Reader %d: shared num = %d\n", num, shared_num); 16 | uv_rwlock_rdunlock(&numlock); 17 | printf("Reader %d: released lock\n", num); 18 | } 19 | uv_barrier_wait(&blocker); 20 | } 21 | 22 | void writer(void *n) 23 | { 24 | int num = *(int *)n; 25 | int i; 26 | for (i = 0; i < 20; i++) { 27 | uv_rwlock_wrlock(&numlock); 28 | printf("Writer %d: acquired lock\n", num); 29 | shared_num++; 30 | printf("Writer %d: incremented shared num = %d\n", num, shared_num); 31 | uv_rwlock_wrunlock(&numlock); 32 | printf("Writer %d: released lock\n", num); 33 | } 34 | uv_barrier_wait(&blocker); 35 | } 36 | 37 | int main() 38 | { 39 | uv_barrier_init(&blocker, 4); 40 | 41 | shared_num = 0; 42 | uv_rwlock_init(&numlock); 43 | 44 | uv_thread_t threads[3]; 45 | 46 | int thread_nums[] = {1, 2, 1}; 47 | uv_thread_create(&threads[0], reader, &thread_nums[0]); 48 | uv_thread_create(&threads[1], reader, &thread_nums[1]); 49 | 50 | uv_thread_create(&threads[2], writer, &thread_nums[2]); 51 | 52 | uv_barrier_wait(&blocker); 53 | uv_barrier_destroy(&blocker); 54 | 55 | uv_rwlock_destroy(&numlock); 56 | return 0; 57 | } 58 | -------------------------------------------------------------------------------- /code/multi-echo-server/hammer.js: -------------------------------------------------------------------------------- 1 | var net = require('net'); 2 | 3 | var PHRASE = "hello world"; 4 | var write = function(socket) { 5 | socket.write(PHRASE, 'utf8'); 6 | } 7 | 8 | for (var i = 0; i < 1000; i++) { 9 | (function() { 10 | var socket = net.connect(7000, 'localhost', function() { 11 | socket.on('data', function(reply) { 12 | if (reply.toString().indexOf(PHRASE) != 0) 13 | console.error("Problem! '" + reply + "'" + " '" + PHRASE + "'"); 14 | else 15 | write(socket); 16 | }); 17 | write(socket); 18 | }); 19 | })(); 20 | } 21 | -------------------------------------------------------------------------------- /code/multi-echo-server/main.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | uv_loop_t *loop; 8 | 9 | struct child_worker { 10 | uv_process_t req; 11 | uv_process_options_t options; 12 | uv_pipe_t pipe; 13 | } *workers; 14 | 15 | int round_robin_counter; 16 | int child_worker_count; 17 | 18 | uv_buf_t dummy_buf; 19 | char worker_path[500]; 20 | 21 | void close_process_handle(uv_process_t *req, int64_t exit_status, int term_signal) { 22 | fprintf(stderr, "Process exited with status %" PRId64 ", signal %d\n", exit_status, term_signal); 23 | uv_close((uv_handle_t*) req, NULL); 24 | } 25 | 26 | void alloc_buffer(uv_handle_t *handle, size_t suggested_size, uv_buf_t *buf) { 27 | buf->base = malloc(suggested_size); 28 | buf->len = suggested_size; 29 | } 30 | 31 | void on_new_connection(uv_stream_t *server, int status) { 32 | if (status == -1) { 33 | // error! 34 | return; 35 | } 36 | 37 | uv_tcp_t *client = (uv_tcp_t*) malloc(sizeof(uv_tcp_t)); 38 | uv_tcp_init(loop, client); 39 | if (uv_accept(server, (uv_stream_t*) client) == 0) { 40 | uv_write_t *write_req = (uv_write_t*) malloc(sizeof(uv_write_t)); 41 | dummy_buf = uv_buf_init("a", 1); 42 | struct child_worker *worker = &workers[round_robin_counter]; 43 | uv_write2(write_req, (uv_stream_t*) &worker->pipe, &dummy_buf, 1, (uv_stream_t*) client, NULL); 44 | round_robin_counter = (round_robin_counter + 1) % child_worker_count; 45 | } 46 | else { 47 | uv_close((uv_handle_t*) client, NULL); 48 | } 49 | } 50 | 51 | void setup_workers() { 52 | size_t path_size = 500; 53 | uv_exepath(worker_path, &path_size); 54 | strcpy(worker_path + (strlen(worker_path) - strlen("multi-echo-server")), "worker"); 55 | fprintf(stderr, "Worker path: %s\n", worker_path); 56 | 57 | char* args[2]; 58 | args[0] = worker_path; 59 | args[1] = NULL; 60 | 61 | round_robin_counter = 0; 62 | 63 | // ... 64 | 65 | // launch same number of workers as number of CPUs 66 | uv_cpu_info_t *info; 67 | int cpu_count; 68 | uv_cpu_info(&info, &cpu_count); 69 | uv_free_cpu_info(info, cpu_count); 70 | 71 | child_worker_count = cpu_count; 72 | 73 | workers = calloc(cpu_count, sizeof(struct child_worker)); 74 | while (cpu_count--) { 75 | struct child_worker *worker = &workers[cpu_count]; 76 | uv_pipe_init(loop, &worker->pipe, 1); 77 | 78 | uv_stdio_container_t child_stdio[3]; 79 | child_stdio[0].flags = UV_CREATE_PIPE | UV_READABLE_PIPE; 80 | child_stdio[0].data.stream = (uv_stream_t*) &worker->pipe; 81 | child_stdio[1].flags = UV_IGNORE; 82 | child_stdio[2].flags = UV_INHERIT_FD; 83 | child_stdio[2].data.fd = 2; 84 | 85 | worker->options.stdio = child_stdio; 86 | worker->options.stdio_count = 3; 87 | 88 | worker->options.exit_cb = close_process_handle; 89 | worker->options.file = args[0]; 90 | worker->options.args = args; 91 | 92 | uv_spawn(loop, &worker->req, &worker->options); 93 | fprintf(stderr, "Started worker %d\n", worker->req.pid); 94 | } 95 | } 96 | 97 | int main() { 98 | loop = uv_default_loop(); 99 | 100 | setup_workers(); 101 | 102 | uv_tcp_t server; 103 | uv_tcp_init(loop, &server); 104 | 105 | struct sockaddr_in bind_addr; 106 | uv_ip4_addr("0.0.0.0", 7000, &bind_addr); 107 | uv_tcp_bind(&server, (const struct sockaddr *)&bind_addr, 0); 108 | int r; 109 | if ((r = uv_listen((uv_stream_t*) &server, 128, on_new_connection))) { 110 | fprintf(stderr, "Listen error %s\n", uv_err_name(r)); 111 | return 2; 112 | } 113 | return uv_run(loop, UV_RUN_DEFAULT); 114 | } 115 | -------------------------------------------------------------------------------- /code/multi-echo-server/worker.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | uv_loop_t *loop; 9 | uv_pipe_t queue; 10 | 11 | typedef struct { 12 | uv_write_t req; 13 | uv_buf_t buf; 14 | } write_req_t; 15 | 16 | void free_write_req(uv_write_t *req) { 17 | write_req_t *wr = (write_req_t*) req; 18 | free(wr->buf.base); 19 | free(wr); 20 | } 21 | 22 | void alloc_buffer(uv_handle_t *handle, size_t suggested_size, uv_buf_t *buf) { 23 | buf->base = malloc(suggested_size); 24 | buf->len = suggested_size; 25 | } 26 | 27 | void echo_write(uv_write_t *req, int status) { 28 | if (status) { 29 | fprintf(stderr, "Write error %s\n", uv_err_name(status)); 30 | } 31 | free_write_req(req); 32 | } 33 | 34 | void echo_read(uv_stream_t *client, ssize_t nread, const uv_buf_t *buf) { 35 | if (nread > 0) { 36 | write_req_t *req = (write_req_t*) malloc(sizeof(write_req_t)); 37 | req->buf = uv_buf_init(buf->base, nread); 38 | uv_write((uv_write_t*) req, client, &req->buf, 1, echo_write); 39 | return; 40 | } 41 | 42 | if (nread < 0) { 43 | if (nread != UV_EOF) 44 | fprintf(stderr, "Read error %s\n", uv_err_name(nread)); 45 | uv_close((uv_handle_t*) client, NULL); 46 | } 47 | 48 | free(buf->base); 49 | } 50 | 51 | void on_new_connection(uv_stream_t *q, ssize_t nread, const uv_buf_t *buf) { 52 | if (nread < 0) { 53 | if (nread != UV_EOF) 54 | fprintf(stderr, "Read error %s\n", uv_err_name(nread)); 55 | uv_close((uv_handle_t*) q, NULL); 56 | return; 57 | } 58 | 59 | uv_pipe_t *pipe = (uv_pipe_t*) q; 60 | if (!uv_pipe_pending_count(pipe)) { 61 | fprintf(stderr, "No pending count\n"); 62 | return; 63 | } 64 | 65 | uv_handle_type pending = uv_pipe_pending_type(pipe); 66 | assert(pending == UV_TCP); 67 | 68 | uv_tcp_t *client = (uv_tcp_t*) malloc(sizeof(uv_tcp_t)); 69 | uv_tcp_init(loop, client); 70 | if (uv_accept(q, (uv_stream_t*) client) == 0) { 71 | uv_os_fd_t fd; 72 | uv_fileno((const uv_handle_t*) client, &fd); 73 | fprintf(stderr, "Worker %d: Accepted fd %d\n", getpid(), fd); 74 | uv_read_start((uv_stream_t*) client, alloc_buffer, echo_read); 75 | } 76 | else { 77 | uv_close((uv_handle_t*) client, NULL); 78 | } 79 | } 80 | 81 | int main() { 82 | loop = uv_default_loop(); 83 | 84 | uv_pipe_init(loop, &queue, 1 /* ipc */); 85 | uv_pipe_open(&queue, 0); 86 | uv_read_start((uv_stream_t*)&queue, alloc_buffer, on_new_connection); 87 | return uv_run(loop, UV_RUN_DEFAULT); 88 | } 89 | -------------------------------------------------------------------------------- /code/onchange/main.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #include 5 | 6 | uv_loop_t *loop; 7 | const char *command; 8 | 9 | void run_command(uv_fs_event_t *handle, const char *filename, int events, int status) { 10 | char path[1024]; 11 | size_t size = 1023; 12 | // Does not handle error if path is longer than 1023. 13 | uv_fs_event_getpath(handle, path, &size); 14 | path[size] = '\0'; 15 | 16 | fprintf(stderr, "Change detected in %s: ", path); 17 | if (events & UV_RENAME) 18 | fprintf(stderr, "renamed"); 19 | if (events & UV_CHANGE) 20 | fprintf(stderr, "changed"); 21 | 22 | fprintf(stderr, " %s\n", filename ? filename : ""); 23 | system(command); 24 | } 25 | 26 | int main(int argc, char **argv) { 27 | if (argc <= 2) { 28 | fprintf(stderr, "Usage: %s [file2 ...]\n", argv[0]); 29 | return 1; 30 | } 31 | 32 | loop = uv_default_loop(); 33 | command = argv[1]; 34 | 35 | while (argc-- > 2) { 36 | fprintf(stderr, "Adding watch on %s\n", argv[argc]); 37 | uv_fs_event_t *fs_event_req = malloc(sizeof(uv_fs_event_t)); 38 | uv_fs_event_init(loop, fs_event_req); 39 | // The recursive flag watches subdirectories too. 40 | uv_fs_event_start(fs_event_req, run_command, argv[argc], UV_FS_EVENT_RECURSIVE); 41 | } 42 | 43 | return uv_run(loop, UV_RUN_DEFAULT); 44 | } 45 | -------------------------------------------------------------------------------- /code/pipe-echo-server/main.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | #ifdef _WIN32 7 | #define PIPENAME "\\\\?\\pipe\\echo.sock" 8 | #else 9 | #define PIPENAME "/tmp/echo.sock" 10 | #endif 11 | 12 | uv_loop_t *loop; 13 | 14 | typedef struct { 15 | uv_write_t req; 16 | uv_buf_t buf; 17 | } write_req_t; 18 | 19 | void free_write_req(uv_write_t *req) { 20 | write_req_t *wr = (write_req_t*) req; 21 | free(wr->buf.base); 22 | free(wr); 23 | } 24 | 25 | void alloc_buffer(uv_handle_t *handle, size_t suggested_size, uv_buf_t *buf) { 26 | buf->base = malloc(suggested_size); 27 | buf->len = suggested_size; 28 | } 29 | 30 | void echo_write(uv_write_t *req, int status) { 31 | if (status < 0) { 32 | fprintf(stderr, "Write error %s\n", uv_err_name(status)); 33 | } 34 | free_write_req(req); 35 | } 36 | 37 | void echo_read(uv_stream_t *client, ssize_t nread, const uv_buf_t *buf) { 38 | if (nread > 0) { 39 | write_req_t *req = (write_req_t*) malloc(sizeof(write_req_t)); 40 | req->buf = uv_buf_init(buf->base, nread); 41 | uv_write((uv_write_t*) req, client, &req->buf, 1, echo_write); 42 | return; 43 | } 44 | 45 | if (nread < 0) { 46 | if (nread != UV_EOF) 47 | fprintf(stderr, "Read error %s\n", uv_err_name(nread)); 48 | uv_close((uv_handle_t*) client, NULL); 49 | } 50 | 51 | free(buf->base); 52 | } 53 | 54 | void on_new_connection(uv_stream_t *server, int status) { 55 | if (status == -1) { 56 | // error! 57 | return; 58 | } 59 | 60 | uv_pipe_t *client = (uv_pipe_t*) malloc(sizeof(uv_pipe_t)); 61 | uv_pipe_init(loop, client, 0); 62 | if (uv_accept(server, (uv_stream_t*) client) == 0) { 63 | uv_read_start((uv_stream_t*) client, alloc_buffer, echo_read); 64 | } 65 | else { 66 | uv_close((uv_handle_t*) client, NULL); 67 | } 68 | } 69 | 70 | void remove_sock(int sig) { 71 | uv_fs_t req; 72 | uv_fs_unlink(loop, &req, PIPENAME, NULL); 73 | exit(0); 74 | } 75 | 76 | int main() { 77 | loop = uv_default_loop(); 78 | 79 | uv_pipe_t server; 80 | uv_pipe_init(loop, &server, 0); 81 | 82 | signal(SIGINT, remove_sock); 83 | 84 | int r; 85 | if ((r = uv_pipe_bind(&server, PIPENAME))) { 86 | fprintf(stderr, "Bind error %s\n", uv_err_name(r)); 87 | return 1; 88 | } 89 | if ((r = uv_listen((uv_stream_t*) &server, 128, on_new_connection))) { 90 | fprintf(stderr, "Listen error %s\n", uv_err_name(r)); 91 | return 2; 92 | } 93 | return uv_run(loop, UV_RUN_DEFAULT); 94 | } 95 | -------------------------------------------------------------------------------- /code/plugin/hello.c: -------------------------------------------------------------------------------- 1 | #include "plugin.h" 2 | 3 | void initialize() { 4 | mfp_register("Hello World!"); 5 | } 6 | -------------------------------------------------------------------------------- /code/plugin/main.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #include 6 | 7 | #include "plugin.h" 8 | 9 | typedef void (*init_plugin_function)(); 10 | 11 | void mfp_register(const char *name) { 12 | fprintf(stderr, "Registered plugin \"%s\"\n", name); 13 | } 14 | 15 | int main(int argc, char **argv) { 16 | if (argc == 1) { 17 | fprintf(stderr, "Usage: %s [plugin1] [plugin2] ...\n", argv[0]); 18 | return 0; 19 | } 20 | 21 | uv_lib_t *lib = (uv_lib_t*) malloc(sizeof(uv_lib_t)); 22 | while (--argc) { 23 | fprintf(stderr, "Loading %s\n", argv[argc]); 24 | if (uv_dlopen(argv[argc], lib)) { 25 | fprintf(stderr, "Error: %s\n", uv_dlerror(lib)); 26 | continue; 27 | } 28 | 29 | init_plugin_function init_plugin; 30 | if (uv_dlsym(lib, "initialize", (void **) &init_plugin)) { 31 | fprintf(stderr, "dlsym error: %s\n", uv_dlerror(lib)); 32 | continue; 33 | } 34 | 35 | init_plugin(); 36 | } 37 | 38 | return 0; 39 | } 40 | -------------------------------------------------------------------------------- /code/plugin/plugin.h: -------------------------------------------------------------------------------- 1 | #ifndef UVBOOK_PLUGIN_SYSTEM 2 | #define UVBOOK_PLUGIN_SYSTEM 3 | 4 | // Plugin authors should use this to register their plugins with mfp. 5 | void mfp_register(const char *name); 6 | 7 | #endif 8 | -------------------------------------------------------------------------------- /code/proc-streams/main.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #include 6 | 7 | uv_loop_t *loop; 8 | uv_process_t child_req; 9 | uv_process_options_t options; 10 | 11 | void on_exit(uv_process_t *req, int64_t exit_status, int term_signal) { 12 | fprintf(stderr, "Process exited with status %" PRId64 ", signal %d\n", exit_status, term_signal); 13 | uv_close((uv_handle_t*) req, NULL); 14 | } 15 | 16 | int main() { 17 | loop = uv_default_loop(); 18 | 19 | size_t size = 500; 20 | char path[size]; 21 | uv_exepath(path, &size); 22 | strcpy(path + (strlen(path) - strlen("proc-streams")), "test"); 23 | 24 | char* args[2]; 25 | args[0] = path; 26 | args[1] = NULL; 27 | 28 | /* ... */ 29 | 30 | options.stdio_count = 3; 31 | uv_stdio_container_t child_stdio[3]; 32 | child_stdio[0].flags = UV_IGNORE; 33 | child_stdio[1].flags = UV_IGNORE; 34 | child_stdio[2].flags = UV_INHERIT_FD; 35 | child_stdio[2].data.fd = 2; 36 | options.stdio = child_stdio; 37 | 38 | options.exit_cb = on_exit; 39 | options.file = args[0]; 40 | options.args = args; 41 | 42 | int r; 43 | if ((r = uv_spawn(loop, &child_req, &options))) { 44 | fprintf(stderr, "%s\n", uv_strerror(r)); 45 | return 1; 46 | } 47 | 48 | return uv_run(loop, UV_RUN_DEFAULT); 49 | } 50 | -------------------------------------------------------------------------------- /code/proc-streams/test.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | fprintf(stderr, "This is stderr\n"); 6 | printf("This is stdout\n"); 7 | return 0; 8 | } 9 | -------------------------------------------------------------------------------- /code/progress/main.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #include 6 | 7 | uv_loop_t *loop; 8 | uv_async_t async; 9 | 10 | double percentage; 11 | 12 | void fake_download(uv_work_t *req) { 13 | int size = *((int*) req->data); 14 | int downloaded = 0; 15 | while (downloaded < size) { 16 | percentage = downloaded*100.0/size; 17 | async.data = (void*) &percentage; 18 | uv_async_send(&async); 19 | 20 | sleep(1); 21 | downloaded += (200+random())%1000; // can only download max 1000bytes/sec, 22 | // but at least a 200; 23 | } 24 | } 25 | 26 | void after(uv_work_t *req, int status) { 27 | fprintf(stderr, "Download complete\n"); 28 | uv_close((uv_handle_t*) &async, NULL); 29 | } 30 | 31 | void print_progress(uv_async_t *handle) { 32 | double percentage = *((double*) handle->data); 33 | fprintf(stderr, "Downloaded %.2f%%\n", percentage); 34 | } 35 | 36 | int main() { 37 | loop = uv_default_loop(); 38 | 39 | uv_work_t req; 40 | int size = 10240; 41 | req.data = (void*) &size; 42 | 43 | uv_async_init(loop, &async, print_progress); 44 | uv_queue_work(loop, &req, fake_download, after); 45 | 46 | return uv_run(loop, UV_RUN_DEFAULT); 47 | } 48 | -------------------------------------------------------------------------------- /code/queue-cancel/main.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #include 6 | 7 | #define FIB_UNTIL 25 8 | uv_loop_t *loop; 9 | uv_work_t fib_reqs[FIB_UNTIL]; 10 | 11 | long fib_(long t) { 12 | if (t == 0 || t == 1) 13 | return 1; 14 | else 15 | return fib_(t-1) + fib_(t-2); 16 | } 17 | 18 | void fib(uv_work_t *req) { 19 | int n = *(int *) req->data; 20 | if (random() % 2) 21 | sleep(1); 22 | else 23 | sleep(3); 24 | long fib = fib_(n); 25 | fprintf(stderr, "%dth fibonacci is %lu\n", n, fib); 26 | } 27 | 28 | void after_fib(uv_work_t *req, int status) { 29 | if (status == UV_ECANCELED) 30 | fprintf(stderr, "Calculation of %d cancelled.\n", *(int *) req->data); 31 | } 32 | 33 | void signal_handler(uv_signal_t *req, int signum) 34 | { 35 | printf("Signal received!\n"); 36 | int i; 37 | for (i = 0; i < FIB_UNTIL; i++) { 38 | uv_cancel((uv_req_t*) &fib_reqs[i]); 39 | } 40 | uv_signal_stop(req); 41 | } 42 | 43 | int main() { 44 | loop = uv_default_loop(); 45 | 46 | int data[FIB_UNTIL]; 47 | int i; 48 | for (i = 0; i < FIB_UNTIL; i++) { 49 | data[i] = i; 50 | fib_reqs[i].data = (void *) &data[i]; 51 | uv_queue_work(loop, &fib_reqs[i], fib, after_fib); 52 | } 53 | 54 | uv_signal_t sig; 55 | uv_signal_init(loop, &sig); 56 | uv_signal_start(&sig, signal_handler, SIGINT); 57 | 58 | return uv_run(loop, UV_RUN_DEFAULT); 59 | } 60 | -------------------------------------------------------------------------------- /code/queue-work/main.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #include 6 | 7 | #define FIB_UNTIL 25 8 | uv_loop_t *loop; 9 | 10 | long fib_(long t) { 11 | if (t == 0 || t == 1) 12 | return 1; 13 | else 14 | return fib_(t-1) + fib_(t-2); 15 | } 16 | 17 | void fib(uv_work_t *req) { 18 | int n = *(int *) req->data; 19 | if (random() % 2) 20 | sleep(1); 21 | else 22 | sleep(3); 23 | long fib = fib_(n); 24 | fprintf(stderr, "%dth fibonacci is %lu\n", n, fib); 25 | } 26 | 27 | void after_fib(uv_work_t *req, int status) { 28 | fprintf(stderr, "Done calculating %dth fibonacci\n", *(int *) req->data); 29 | } 30 | 31 | int main() { 32 | loop = uv_default_loop(); 33 | 34 | int data[FIB_UNTIL]; 35 | uv_work_t req[FIB_UNTIL]; 36 | int i; 37 | for (i = 0; i < FIB_UNTIL; i++) { 38 | data[i] = i; 39 | req[i].data = (void *) &data[i]; 40 | uv_queue_work(loop, &req[i], fib, after_fib); 41 | } 42 | 43 | return uv_run(loop, UV_RUN_DEFAULT); 44 | } 45 | -------------------------------------------------------------------------------- /code/ref-timer/main.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include 4 | 5 | uv_loop_t *loop; 6 | uv_timer_t gc_req; 7 | uv_timer_t fake_job_req; 8 | 9 | void gc(uv_timer_t *handle) { 10 | fprintf(stderr, "Freeing unused objects\n"); 11 | } 12 | 13 | void fake_job(uv_timer_t *handle) { 14 | fprintf(stdout, "Fake job done\n"); 15 | } 16 | 17 | int main() { 18 | loop = uv_default_loop(); 19 | 20 | uv_timer_init(loop, &gc_req); 21 | uv_unref((uv_handle_t*) &gc_req); 22 | 23 | uv_timer_start(&gc_req, gc, 0, 2000); 24 | 25 | // could actually be a TCP download or something 26 | uv_timer_init(loop, &fake_job_req); 27 | uv_timer_start(&fake_job_req, fake_job, 9000, 0); 28 | return uv_run(loop, UV_RUN_DEFAULT); 29 | } 30 | -------------------------------------------------------------------------------- /code/signal/main.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | uv_loop_t* create_loop() 7 | { 8 | uv_loop_t *loop = malloc(sizeof(uv_loop_t)); 9 | if (loop) { 10 | uv_loop_init(loop); 11 | } 12 | return loop; 13 | } 14 | 15 | void signal_handler(uv_signal_t *handle, int signum) 16 | { 17 | printf("Signal received: %d\n", signum); 18 | uv_signal_stop(handle); 19 | } 20 | 21 | // two signal handlers in one loop 22 | void thread1_worker(void *userp) 23 | { 24 | uv_loop_t *loop1 = create_loop(); 25 | 26 | uv_signal_t sig1a, sig1b; 27 | uv_signal_init(loop1, &sig1a); 28 | uv_signal_start(&sig1a, signal_handler, SIGUSR1); 29 | 30 | uv_signal_init(loop1, &sig1b); 31 | uv_signal_start(&sig1b, signal_handler, SIGUSR1); 32 | 33 | uv_run(loop1, UV_RUN_DEFAULT); 34 | } 35 | 36 | // two signal handlers, each in its own loop 37 | void thread2_worker(void *userp) 38 | { 39 | uv_loop_t *loop2 = create_loop(); 40 | uv_loop_t *loop3 = create_loop(); 41 | 42 | uv_signal_t sig2; 43 | uv_signal_init(loop2, &sig2); 44 | uv_signal_start(&sig2, signal_handler, SIGUSR1); 45 | 46 | uv_signal_t sig3; 47 | uv_signal_init(loop3, &sig3); 48 | uv_signal_start(&sig3, signal_handler, SIGUSR1); 49 | 50 | while (uv_run(loop2, UV_RUN_NOWAIT) || uv_run(loop3, UV_RUN_NOWAIT)) { 51 | } 52 | } 53 | 54 | int main() 55 | { 56 | printf("PID %d\n", getpid()); 57 | 58 | uv_thread_t thread1, thread2; 59 | 60 | uv_thread_create(&thread1, thread1_worker, 0); 61 | uv_thread_create(&thread2, thread2_worker, 0); 62 | 63 | uv_thread_join(&thread1); 64 | uv_thread_join(&thread2); 65 | return 0; 66 | } 67 | -------------------------------------------------------------------------------- /code/spawn/main.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #include 5 | 6 | uv_loop_t *loop; 7 | uv_process_t child_req; 8 | uv_process_options_t options; 9 | 10 | void on_exit(uv_process_t *req, int64_t exit_status, int term_signal) { 11 | fprintf(stderr, "Process exited with status %" PRId64 ", signal %d\n", exit_status, term_signal); 12 | uv_close((uv_handle_t*) req, NULL); 13 | } 14 | 15 | int main() { 16 | loop = uv_default_loop(); 17 | 18 | char* args[3]; 19 | args[0] = "mkdir"; 20 | args[1] = "test-dir"; 21 | args[2] = NULL; 22 | 23 | options.exit_cb = on_exit; 24 | options.file = "mkdir"; 25 | options.args = args; 26 | 27 | int r; 28 | if ((r = uv_spawn(loop, &child_req, &options))) { 29 | fprintf(stderr, "%s\n", uv_strerror(r)); 30 | return 1; 31 | } else { 32 | fprintf(stderr, "Launched process with ID %d\n", child_req.pid); 33 | } 34 | 35 | return uv_run(loop, UV_RUN_DEFAULT); 36 | } 37 | -------------------------------------------------------------------------------- /code/tcp-echo-server/main.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | #define DEFAULT_PORT 7000 7 | #define DEFAULT_BACKLOG 128 8 | 9 | uv_loop_t *loop; 10 | struct sockaddr_in addr; 11 | 12 | typedef struct { 13 | uv_write_t req; 14 | uv_buf_t buf; 15 | } write_req_t; 16 | 17 | void free_write_req(uv_write_t *req) { 18 | write_req_t *wr = (write_req_t*) req; 19 | free(wr->buf.base); 20 | free(wr); 21 | } 22 | 23 | void alloc_buffer(uv_handle_t *handle, size_t suggested_size, uv_buf_t *buf) { 24 | buf->base = (char*) malloc(suggested_size); 25 | buf->len = suggested_size; 26 | } 27 | 28 | void on_close(uv_handle_t* handle) { 29 | free(handle); 30 | } 31 | 32 | void echo_write(uv_write_t *req, int status) { 33 | if (status) { 34 | fprintf(stderr, "Write error %s\n", uv_strerror(status)); 35 | } 36 | free_write_req(req); 37 | } 38 | 39 | void echo_read(uv_stream_t *client, ssize_t nread, const uv_buf_t *buf) { 40 | if (nread > 0) { 41 | write_req_t *req = (write_req_t*) malloc(sizeof(write_req_t)); 42 | req->buf = uv_buf_init(buf->base, nread); 43 | uv_write((uv_write_t*) req, client, &req->buf, 1, echo_write); 44 | return; 45 | } 46 | if (nread < 0) { 47 | if (nread != UV_EOF) 48 | fprintf(stderr, "Read error %s\n", uv_err_name(nread)); 49 | uv_close((uv_handle_t*) client, on_close); 50 | } 51 | 52 | free(buf->base); 53 | } 54 | 55 | void on_new_connection(uv_stream_t *server, int status) { 56 | if (status < 0) { 57 | fprintf(stderr, "New connection error %s\n", uv_strerror(status)); 58 | // error! 59 | return; 60 | } 61 | 62 | uv_tcp_t *client = (uv_tcp_t*) malloc(sizeof(uv_tcp_t)); 63 | uv_tcp_init(loop, client); 64 | if (uv_accept(server, (uv_stream_t*) client) == 0) { 65 | uv_read_start((uv_stream_t*) client, alloc_buffer, echo_read); 66 | } 67 | else { 68 | uv_close((uv_handle_t*) client, on_close); 69 | } 70 | } 71 | 72 | int main() { 73 | loop = uv_default_loop(); 74 | 75 | uv_tcp_t server; 76 | uv_tcp_init(loop, &server); 77 | 78 | uv_ip4_addr("0.0.0.0", DEFAULT_PORT, &addr); 79 | 80 | uv_tcp_bind(&server, (const struct sockaddr*)&addr, 0); 81 | int r = uv_listen((uv_stream_t*) &server, DEFAULT_BACKLOG, on_new_connection); 82 | if (r) { 83 | fprintf(stderr, "Listen error %s\n", uv_strerror(r)); 84 | return 1; 85 | } 86 | return uv_run(loop, UV_RUN_DEFAULT); 87 | } 88 | -------------------------------------------------------------------------------- /code/thread-create/main.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #include 5 | 6 | void hare(void *arg) { 7 | int tracklen = *((int *) arg); 8 | while (tracklen) { 9 | tracklen--; 10 | sleep(1); 11 | fprintf(stderr, "Hare ran another step\n"); 12 | } 13 | fprintf(stderr, "Hare done running!\n"); 14 | } 15 | 16 | void tortoise(void *arg) { 17 | int tracklen = *((int *) arg); 18 | while (tracklen) { 19 | tracklen--; 20 | fprintf(stderr, "Tortoise ran another step\n"); 21 | sleep(3); 22 | } 23 | fprintf(stderr, "Tortoise done running!\n"); 24 | } 25 | 26 | int main() { 27 | int tracklen = 10; 28 | uv_thread_t hare_id; 29 | uv_thread_t tortoise_id; 30 | uv_thread_create(&hare_id, hare, &tracklen); 31 | uv_thread_create(&tortoise_id, tortoise, &tracklen); 32 | 33 | uv_thread_join(&hare_id); 34 | uv_thread_join(&tortoise_id); 35 | return 0; 36 | } 37 | -------------------------------------------------------------------------------- /code/tty-gravity/main.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | uv_loop_t *loop; 7 | uv_tty_t tty; 8 | uv_timer_t tick; 9 | uv_write_t write_req; 10 | int width, height; 11 | int pos = 0; 12 | char *message = " Hello TTY "; 13 | 14 | void update(uv_timer_t *req) { 15 | char data[500]; 16 | 17 | uv_buf_t buf; 18 | buf.base = data; 19 | buf.len = sprintf(data, "\033[2J\033[H\033[%dB\033[%luC\033[42;37m%s", 20 | pos, 21 | (unsigned long) (width-strlen(message))/2, 22 | message); 23 | uv_write(&write_req, (uv_stream_t*) &tty, &buf, 1, NULL); 24 | 25 | pos++; 26 | if (pos > height) { 27 | uv_tty_reset_mode(); 28 | uv_timer_stop(&tick); 29 | } 30 | } 31 | 32 | int main() { 33 | loop = uv_default_loop(); 34 | 35 | uv_tty_init(loop, &tty, STDOUT_FILENO, 0); 36 | uv_tty_set_mode(&tty, 0); 37 | 38 | if (uv_tty_get_winsize(&tty, &width, &height)) { 39 | fprintf(stderr, "Could not get TTY information\n"); 40 | uv_tty_reset_mode(); 41 | return 1; 42 | } 43 | 44 | fprintf(stderr, "Width %d, height %d\n", width, height); 45 | uv_timer_init(loop, &tick); 46 | uv_timer_start(&tick, update, 200, 200); 47 | return uv_run(loop, UV_RUN_DEFAULT); 48 | } 49 | -------------------------------------------------------------------------------- /code/tty/main.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | uv_loop_t *loop; 7 | uv_tty_t tty; 8 | int main() { 9 | loop = uv_default_loop(); 10 | 11 | uv_tty_init(loop, &tty, STDOUT_FILENO, 0); 12 | uv_tty_set_mode(&tty, UV_TTY_MODE_NORMAL); 13 | 14 | if (uv_guess_handle(1) == UV_TTY) { 15 | uv_write_t req; 16 | uv_buf_t buf; 17 | buf.base = "\033[41;37m"; 18 | buf.len = strlen(buf.base); 19 | uv_write(&req, (uv_stream_t*) &tty, &buf, 1, NULL); 20 | } 21 | 22 | uv_write_t req; 23 | uv_buf_t buf; 24 | buf.base = "Hello TTY\n"; 25 | buf.len = strlen(buf.base); 26 | uv_write(&req, (uv_stream_t*) &tty, &buf, 1, NULL); 27 | uv_tty_reset_mode(); 28 | return uv_run(loop, UV_RUN_DEFAULT); 29 | } 30 | -------------------------------------------------------------------------------- /code/udp-dhcp/main.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | #include 7 | 8 | uv_loop_t *loop; 9 | uv_udp_t send_socket; 10 | uv_udp_t recv_socket; 11 | 12 | void alloc_buffer(uv_handle_t *handle, size_t suggested_size, uv_buf_t *buf) { 13 | buf->base = malloc(suggested_size); 14 | buf->len = suggested_size; 15 | } 16 | 17 | void on_read(uv_udp_t *req, ssize_t nread, const uv_buf_t *buf, const struct sockaddr *addr, unsigned flags) { 18 | if (nread < 0) { 19 | fprintf(stderr, "Read error %s\n", uv_err_name(nread)); 20 | uv_close((uv_handle_t*) req, NULL); 21 | free(buf->base); 22 | return; 23 | } 24 | 25 | char sender[17] = { 0 }; 26 | uv_ip4_name((const struct sockaddr_in*) addr, sender, 16); 27 | fprintf(stderr, "Recv from %s\n", sender); 28 | 29 | // ... DHCP specific code 30 | unsigned int *as_integer = (unsigned int*)buf->base; 31 | unsigned int ipbin = ntohl(as_integer[4]); 32 | unsigned char ip[4] = {0}; 33 | int i; 34 | for (i = 0; i < 4; i++) 35 | ip[i] = (ipbin >> i*8) & 0xff; 36 | fprintf(stderr, "Offered IP %d.%d.%d.%d\n", ip[3], ip[2], ip[1], ip[0]); 37 | 38 | free(buf->base); 39 | uv_udp_recv_stop(req); 40 | } 41 | 42 | uv_buf_t make_discover_msg() { 43 | uv_buf_t buffer; 44 | alloc_buffer(NULL, 256, &buffer); 45 | memset(buffer.base, 0, buffer.len); 46 | 47 | // BOOTREQUEST 48 | buffer.base[0] = 0x1; 49 | // HTYPE ethernet 50 | buffer.base[1] = 0x1; 51 | // HLEN 52 | buffer.base[2] = 0x6; 53 | // HOPS 54 | buffer.base[3] = 0x0; 55 | // XID 4 bytes 56 | buffer.base[4] = (unsigned int) random(); 57 | // SECS 58 | buffer.base[8] = 0x0; 59 | // FLAGS 60 | buffer.base[10] = 0x80; 61 | // CIADDR 12-15 is all zeros 62 | // YIADDR 16-19 is all zeros 63 | // SIADDR 20-23 is all zeros 64 | // GIADDR 24-27 is all zeros 65 | // CHADDR 28-43 is the MAC address, use your own 66 | buffer.base[28] = 0xe4; 67 | buffer.base[29] = 0xce; 68 | buffer.base[30] = 0x8f; 69 | buffer.base[31] = 0x13; 70 | buffer.base[32] = 0xf6; 71 | buffer.base[33] = 0xd4; 72 | // SNAME 64 bytes zero 73 | // FILE 128 bytes zero 74 | // OPTIONS 75 | // - magic cookie 76 | buffer.base[236] = 99; 77 | buffer.base[237] = 130; 78 | buffer.base[238] = 83; 79 | buffer.base[239] = 99; 80 | 81 | // DHCP Message type 82 | buffer.base[240] = 53; 83 | buffer.base[241] = 1; 84 | buffer.base[242] = 1; // DHCPDISCOVER 85 | 86 | // DHCP Parameter request list 87 | buffer.base[243] = 55; 88 | buffer.base[244] = 4; 89 | buffer.base[245] = 1; 90 | buffer.base[246] = 3; 91 | buffer.base[247] = 15; 92 | buffer.base[248] = 6; 93 | 94 | return buffer; 95 | } 96 | 97 | void on_send(uv_udp_send_t *req, int status) { 98 | if (status) { 99 | fprintf(stderr, "Send error %s\n", uv_strerror(status)); 100 | return; 101 | } 102 | } 103 | 104 | int main() { 105 | loop = uv_default_loop(); 106 | 107 | uv_udp_init(loop, &recv_socket); 108 | struct sockaddr_in recv_addr; 109 | uv_ip4_addr("0.0.0.0", 68, &recv_addr); 110 | uv_udp_bind(&recv_socket, (const struct sockaddr *)&recv_addr, UV_UDP_REUSEADDR); 111 | uv_udp_recv_start(&recv_socket, alloc_buffer, on_read); 112 | 113 | uv_udp_init(loop, &send_socket); 114 | struct sockaddr_in broadcast_addr; 115 | uv_ip4_addr("0.0.0.0", 0, &broadcast_addr); 116 | uv_udp_bind(&send_socket, (const struct sockaddr *)&broadcast_addr, 0); 117 | uv_udp_set_broadcast(&send_socket, 1); 118 | 119 | uv_udp_send_t send_req; 120 | uv_buf_t discover_msg = make_discover_msg(); 121 | 122 | struct sockaddr_in send_addr; 123 | uv_ip4_addr("255.255.255.255", 67, &send_addr); 124 | uv_udp_send(&send_req, &send_socket, &discover_msg, 1, (const struct sockaddr *)&send_addr, on_send); 125 | 126 | return uv_run(loop, UV_RUN_DEFAULT); 127 | } 128 | -------------------------------------------------------------------------------- /code/uvcat/main.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | void on_read(uv_fs_t *req); 8 | 9 | uv_fs_t open_req; 10 | uv_fs_t read_req; 11 | uv_fs_t write_req; 12 | 13 | static char buffer[1024]; 14 | 15 | static uv_buf_t iov; 16 | 17 | void on_write(uv_fs_t *req) { 18 | if (req->result < 0) { 19 | fprintf(stderr, "Write error: %s\n", uv_strerror((int)req->result)); 20 | } 21 | else { 22 | uv_fs_read(uv_default_loop(), &read_req, open_req.result, &iov, 1, -1, on_read); 23 | } 24 | } 25 | 26 | void on_read(uv_fs_t *req) { 27 | if (req->result < 0) { 28 | fprintf(stderr, "Read error: %s\n", uv_strerror(req->result)); 29 | } 30 | else if (req->result == 0) { 31 | uv_fs_t close_req; 32 | // synchronous 33 | uv_fs_close(uv_default_loop(), &close_req, open_req.result, NULL); 34 | } 35 | else if (req->result > 0) { 36 | iov.len = req->result; 37 | uv_fs_write(uv_default_loop(), &write_req, 1, &iov, 1, -1, on_write); 38 | } 39 | } 40 | 41 | void on_open(uv_fs_t *req) { 42 | // The request passed to the callback is the same as the one the call setup 43 | // function was passed. 44 | assert(req == &open_req); 45 | if (req->result >= 0) { 46 | iov = uv_buf_init(buffer, sizeof(buffer)); 47 | uv_fs_read(uv_default_loop(), &read_req, req->result, 48 | &iov, 1, -1, on_read); 49 | } 50 | else { 51 | fprintf(stderr, "error opening file: %s\n", uv_strerror((int)req->result)); 52 | } 53 | } 54 | 55 | int main(int argc, char **argv) { 56 | uv_fs_open(uv_default_loop(), &open_req, argv[1], O_RDONLY, 0, on_open); 57 | uv_run(uv_default_loop(), UV_RUN_DEFAULT); 58 | 59 | uv_fs_req_cleanup(&open_req); 60 | uv_fs_req_cleanup(&read_req); 61 | uv_fs_req_cleanup(&write_req); 62 | return 0; 63 | } 64 | -------------------------------------------------------------------------------- /code/uvstop/main.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int64_t counter = 0; 5 | 6 | void idle_cb(uv_idle_t *handle) { 7 | printf("Idle callback\n"); 8 | counter++; 9 | 10 | if (counter >= 5) { 11 | uv_stop(uv_default_loop()); 12 | printf("uv_stop() called\n"); 13 | } 14 | } 15 | 16 | void prep_cb(uv_prepare_t *handle) { 17 | printf("Prep callback\n"); 18 | } 19 | 20 | int main() { 21 | uv_idle_t idler; 22 | uv_prepare_t prep; 23 | 24 | uv_idle_init(uv_default_loop(), &idler); 25 | uv_idle_start(&idler, idle_cb); 26 | 27 | uv_prepare_init(uv_default_loop(), &prep); 28 | uv_prepare_start(&prep, prep_cb); 29 | 30 | uv_run(uv_default_loop(), UV_RUN_DEFAULT); 31 | 32 | return 0; 33 | } 34 | -------------------------------------------------------------------------------- /code/uvtee/main.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | #include 8 | 9 | typedef struct { 10 | uv_write_t req; 11 | uv_buf_t buf; 12 | } write_req_t; 13 | 14 | uv_loop_t *loop; 15 | uv_pipe_t stdin_pipe; 16 | uv_pipe_t stdout_pipe; 17 | uv_pipe_t file_pipe; 18 | 19 | void alloc_buffer(uv_handle_t *handle, size_t suggested_size, uv_buf_t *buf) { 20 | *buf = uv_buf_init((char*) malloc(suggested_size), suggested_size); 21 | } 22 | 23 | void free_write_req(uv_write_t *req) { 24 | write_req_t *wr = (write_req_t*) req; 25 | free(wr->buf.base); 26 | free(wr); 27 | } 28 | 29 | void on_stdout_write(uv_write_t *req, int status) { 30 | free_write_req(req); 31 | } 32 | 33 | void on_file_write(uv_write_t *req, int status) { 34 | free_write_req(req); 35 | } 36 | 37 | void write_data(uv_stream_t *dest, size_t size, uv_buf_t buf, uv_write_cb cb) { 38 | write_req_t *req = (write_req_t*) malloc(sizeof(write_req_t)); 39 | req->buf = uv_buf_init((char*) malloc(size), size); 40 | memcpy(req->buf.base, buf.base, size); 41 | uv_write((uv_write_t*) req, (uv_stream_t*)dest, &req->buf, 1, cb); 42 | } 43 | 44 | void read_stdin(uv_stream_t *stream, ssize_t nread, const uv_buf_t *buf) { 45 | if (nread < 0){ 46 | if (nread == UV_EOF){ 47 | // end of file 48 | uv_close((uv_handle_t *)&stdin_pipe, NULL); 49 | uv_close((uv_handle_t *)&stdout_pipe, NULL); 50 | uv_close((uv_handle_t *)&file_pipe, NULL); 51 | } 52 | } else if (nread > 0) { 53 | write_data((uv_stream_t *)&stdout_pipe, nread, *buf, on_stdout_write); 54 | write_data((uv_stream_t *)&file_pipe, nread, *buf, on_file_write); 55 | } 56 | 57 | // OK to free buffer as write_data copies it. 58 | if (buf->base) 59 | free(buf->base); 60 | } 61 | 62 | int main(int argc, char **argv) { 63 | loop = uv_default_loop(); 64 | 65 | uv_pipe_init(loop, &stdin_pipe, 0); 66 | uv_pipe_open(&stdin_pipe, 0); 67 | 68 | uv_pipe_init(loop, &stdout_pipe, 0); 69 | uv_pipe_open(&stdout_pipe, 1); 70 | 71 | uv_fs_t file_req; 72 | int fd = uv_fs_open(loop, &file_req, argv[1], O_CREAT | O_RDWR, 0644, NULL); 73 | uv_pipe_init(loop, &file_pipe, 0); 74 | uv_pipe_open(&file_pipe, fd); 75 | 76 | uv_read_start((uv_stream_t*)&stdin_pipe, alloc_buffer, read_stdin); 77 | 78 | uv_run(loop, UV_RUN_DEFAULT); 79 | return 0; 80 | } 81 | -------------------------------------------------------------------------------- /code/uvwget/main.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | uv_loop_t *loop; 8 | CURLM *curl_handle; 9 | uv_timer_t timeout; 10 | 11 | typedef struct curl_context_s { 12 | uv_poll_t poll_handle; 13 | curl_socket_t sockfd; 14 | } curl_context_t; 15 | 16 | curl_context_t *create_curl_context(curl_socket_t sockfd) { 17 | curl_context_t *context; 18 | 19 | context = (curl_context_t*) malloc(sizeof *context); 20 | 21 | context->sockfd = sockfd; 22 | 23 | int r = uv_poll_init_socket(loop, &context->poll_handle, sockfd); 24 | assert(r == 0); 25 | context->poll_handle.data = context; 26 | 27 | return context; 28 | } 29 | 30 | void curl_close_cb(uv_handle_t *handle) { 31 | curl_context_t *context = (curl_context_t*) handle->data; 32 | free(context); 33 | } 34 | 35 | void destroy_curl_context(curl_context_t *context) { 36 | uv_close((uv_handle_t*) &context->poll_handle, curl_close_cb); 37 | } 38 | 39 | 40 | void add_download(const char *url, int num) { 41 | char filename[50]; 42 | sprintf(filename, "%d.download", num); 43 | FILE *file; 44 | 45 | file = fopen(filename, "w"); 46 | if (file == NULL) { 47 | fprintf(stderr, "Error opening %s\n", filename); 48 | return; 49 | } 50 | 51 | CURL *handle = curl_easy_init(); 52 | curl_easy_setopt(handle, CURLOPT_WRITEDATA, file); 53 | curl_easy_setopt(handle, CURLOPT_URL, url); 54 | curl_multi_add_handle(curl_handle, handle); 55 | fprintf(stderr, "Added download %s -> %s\n", url, filename); 56 | } 57 | 58 | void check_multi_info(void) { 59 | char *done_url; 60 | CURLMsg *message; 61 | int pending; 62 | 63 | while ((message = curl_multi_info_read(curl_handle, &pending))) { 64 | switch (message->msg) { 65 | case CURLMSG_DONE: 66 | curl_easy_getinfo(message->easy_handle, CURLINFO_EFFECTIVE_URL, 67 | &done_url); 68 | printf("%s DONE\n", done_url); 69 | 70 | curl_multi_remove_handle(curl_handle, message->easy_handle); 71 | curl_easy_cleanup(message->easy_handle); 72 | break; 73 | 74 | default: 75 | fprintf(stderr, "CURLMSG default\n"); 76 | abort(); 77 | } 78 | } 79 | } 80 | 81 | void curl_perform(uv_poll_t *req, int status, int events) { 82 | uv_timer_stop(&timeout); 83 | int running_handles; 84 | int flags = 0; 85 | if (status < 0) flags = CURL_CSELECT_ERR; 86 | if (!status && events & UV_READABLE) flags |= CURL_CSELECT_IN; 87 | if (!status && events & UV_WRITABLE) flags |= CURL_CSELECT_OUT; 88 | 89 | curl_context_t *context; 90 | 91 | context = (curl_context_t*)req; 92 | 93 | curl_multi_socket_action(curl_handle, context->sockfd, flags, &running_handles); 94 | check_multi_info(); 95 | } 96 | 97 | void on_timeout(uv_timer_t *req) { 98 | int running_handles; 99 | curl_multi_socket_action(curl_handle, CURL_SOCKET_TIMEOUT, 0, &running_handles); 100 | check_multi_info(); 101 | } 102 | 103 | void start_timeout(CURLM *multi, long timeout_ms, void *userp) { 104 | if (timeout_ms <= 0) 105 | timeout_ms = 1; /* 0 means directly call socket_action, but we'll do it in a bit */ 106 | uv_timer_start(&timeout, on_timeout, timeout_ms, 0); 107 | } 108 | 109 | int handle_socket(CURL *easy, curl_socket_t s, int action, void *userp, void *socketp) { 110 | curl_context_t *curl_context; 111 | if (action == CURL_POLL_IN || action == CURL_POLL_OUT) { 112 | if (socketp) { 113 | curl_context = (curl_context_t*) socketp; 114 | } 115 | else { 116 | curl_context = create_curl_context(s); 117 | curl_multi_assign(curl_handle, s, (void *) curl_context); 118 | } 119 | } 120 | 121 | switch (action) { 122 | case CURL_POLL_IN: 123 | uv_poll_start(&curl_context->poll_handle, UV_READABLE, curl_perform); 124 | break; 125 | case CURL_POLL_OUT: 126 | uv_poll_start(&curl_context->poll_handle, UV_WRITABLE, curl_perform); 127 | break; 128 | case CURL_POLL_REMOVE: 129 | if (socketp) { 130 | uv_poll_stop(&((curl_context_t*)socketp)->poll_handle); 131 | destroy_curl_context((curl_context_t*) socketp); 132 | curl_multi_assign(curl_handle, s, NULL); 133 | } 134 | break; 135 | default: 136 | abort(); 137 | } 138 | 139 | return 0; 140 | } 141 | 142 | int main(int argc, char **argv) { 143 | loop = uv_default_loop(); 144 | 145 | if (argc <= 1) 146 | return 0; 147 | 148 | if (curl_global_init(CURL_GLOBAL_ALL)) { 149 | fprintf(stderr, "Could not init cURL\n"); 150 | return 1; 151 | } 152 | 153 | uv_timer_init(loop, &timeout); 154 | 155 | curl_handle = curl_multi_init(); 156 | curl_multi_setopt(curl_handle, CURLMOPT_SOCKETFUNCTION, handle_socket); 157 | curl_multi_setopt(curl_handle, CURLMOPT_TIMERFUNCTION, start_timeout); 158 | 159 | while (argc-- > 1) { 160 | add_download(argv[argc], argc); 161 | } 162 | 163 | uv_run(loop, UV_RUN_DEFAULT); 164 | curl_multi_cleanup(curl_handle); 165 | return 0; 166 | } 167 | -------------------------------------------------------------------------------- /source/about.md: -------------------------------------------------------------------------------- 1 | # About 2 | 3 | [Nikhil Marathe](http://nikhilism.com)在某一个下午(June 16, 2012)开始写这本书。当他在写[node-taglib](https://github.com/nikhilm/node-taglib)的时候苦于没有好的libuv文档。虽然已经有了官方文档,但是没有好理解的教程。本书正是应需求而生,并且努力变得准确。也就是说,本书中可能会有错误。所以鼓励大家Pull requests。你当然可以直接给他发[email](nsm.nikhil%40gmail.com),告诉他错误。 4 | 5 | Nikhil从Marc Lehmann的关于libev的[手册](http://pod.tst.eu/http://cvs.schmorp.de/libev/ev.pod)中讲解libev和libuv的不同点的部分,获取了不少的灵感。 6 | 7 | 本书的中文翻译者在[这里](https://github.com/luohaha/Chinese-uvbook/graphs/contributors)。同样欢迎您的Pull requests来改进本书的翻译工作。 8 | 9 | ### Licensing 10 | 11 | The contents of this book are licensed as [Creative Commons - Attribution](http://creativecommons.org/licenses/by/3.0/). All code is in the public domain. 12 | -------------------------------------------------------------------------------- /source/advanced-event-loops.md: -------------------------------------------------------------------------------- 1 | # Advanced event loops 2 | 3 | libuv提供了非常多的控制event-loop的方法,你能通过使用多loop来实现很多有趣的功能。你还可以将libuv的event loop嵌入到其它基于event-loop的库中。比如,想象着一个基于Qt的UI,然后Qt的event-loop是由libuv驱动的,做着加强级的系统任务。 4 | 5 | ## Stopping an event loop 6 | 7 | `uv_stop()`用来终止event loop。loop会停止的最早时间点是在下次循环的时候,或者稍晚些的时候。这也就意味着在本次循环中已经准备被处理的事件,依然会被处理,`uv_stop`不会起到作用。当`uv_stop`被调用,在当前的循环中,loop不会被IO操作阻塞。上面这些说得有点玄乎,还是让我们看下`uv_run()`的代码: 8 | 9 | #### src/unix/core.c - uv_run 10 | 11 | ```c 12 | int uv_run(uv_loop_t* loop, uv_run_mode mode) { 13 | int timeout; 14 | int r; 15 | int ran_pending; 16 | 17 | r = uv__loop_alive(loop); 18 | if (!r) 19 | uv__update_time(loop); 20 | 21 | while (r != 0 && loop->stop_flag == 0) { 22 | uv__update_time(loop); 23 | uv__run_timers(loop); 24 | ran_pending = uv__run_pending(loop); 25 | uv__run_idle(loop); 26 | uv__run_prepare(loop); 27 | 28 | timeout = 0; 29 | if ((mode == UV_RUN_ONCE && !ran_pending) || mode == UV_RUN_DEFAULT) 30 | timeout = uv_backend_timeout(loop); 31 | 32 | uv__io_poll(loop, timeout); 33 | ``` 34 | 35 | `stop_flag`由`uv_stop`设置。现在所有的libuv回调函数都是在一次loop循环中被调用的,因此调用`uv_stop`并不能中止本次循环。首先,libuv会更新定时器,然后运行接下来的定时器,空转和准备回调,调用任何准备好的IO回调函数。如果你在它们之间的任何一个时间里,调用`uv_stop()`,`stop_flag`会被设置为1。这会导致`uv_backend_timeout()`返回0,这也就是为什么loop不会阻塞在I/O上。从另外的角度来说,你在任何一个检查handler中调用`uv_stop`,此时I/O已经完成,所以也没有影响。 36 | 37 | 在已经得到结果,或是发生错误的时候,`uv_stop()`可以用来关闭一个loop,而且不需要保证handler停止的顺序。 38 | 39 | 下面是一个简单的例子,它演示了loop的停止,以及当前的循环依旧在执行。 40 | 41 | #### uvstop/main.c 42 | 43 | ```c 44 | #include 45 | #include 46 | 47 | int64_t counter = 0; 48 | 49 | void idle_cb(uv_idle_t *handle) { 50 | printf("Idle callback\n"); 51 | counter++; 52 | 53 | if (counter >= 5) { 54 | uv_stop(uv_default_loop()); 55 | printf("uv_stop() called\n"); 56 | } 57 | } 58 | 59 | void prep_cb(uv_prepare_t *handle) { 60 | printf("Prep callback\n"); 61 | } 62 | 63 | int main() { 64 | uv_idle_t idler; 65 | uv_prepare_t prep; 66 | 67 | uv_idle_init(uv_default_loop(), &idler); 68 | uv_idle_start(&idler, idle_cb); 69 | 70 | uv_prepare_init(uv_default_loop(), &prep); 71 | uv_prepare_start(&prep, prep_cb); 72 | 73 | uv_run(uv_default_loop(), UV_RUN_DEFAULT); 74 | 75 | return 0; 76 | } 77 | ``` 78 | 79 | -------------------------------------------------------------------------------- /source/basics_of_libuv.md: -------------------------------------------------------------------------------- 1 | # Basics of libuv 2 | 3 | libuv强制使用异步和事件驱动的编程风格。它的核心工作是提供一个event-loop,还有基于I/O和其它事件通知的回调函数。libuv还提供了一些核心工具,例如定时器,非阻塞的网络支持,异步文件系统访问,子进程等。 4 | 5 | ## Event loops 6 | 7 | 在事件驱动编程中,程序会关注每一个事件,并且对每一个事件的发生做出反应。libuv会负责将来自操作系统的事件收集起来,或者监视其他来源的事件。这样,用户就可以注册回调函数,回调函数会在事件发生的时候被调用。event-loop会一直保持运行状态。用伪代码描述如下: 8 | 9 | ```c 10 | while there are still events to process: 11 | e = get the next event 12 | if there is a callback associated with e: 13 | call the callback 14 | ``` 15 | 16 | 举几个事件的例子: 17 | >* 准备好被写入的文件。 18 | >* 包含准备被读取的数据的socket。 19 | >* 超时的定时器。 20 | 21 | event-loop最终会被`uv_run()`启动-当使用libuv时,最后都会调用的函数。 22 | 23 | 系统编程中最经常处理的一般是输入和输出,而不是一大堆的数据处理。问题在于传统的输入/输出函数(例如`read`,`fprintf`)都是阻塞式的。实际上,向文件写入数据,从网络读取数据所花的时间,对比CPU的处理速度差得太多。任务没有完成,函数是不会返回的,所以你的程序在这段时间内什么也做不了。对于需要高性能的的程序来说,这是一个主要的障碍因为其他活动和I/O操作都在保持等待。 24 | 25 | 其中一个标准的解决方案是使用多线程。每一个阻塞的I/O操作都会被分配到各个线程中(或者是使用线程池)。当某个线程一旦阻塞,处理器就可以调度处理其他需要cpu资源的线程。 26 | 27 | 但是libuv使用了另外一个解决方案,那就是异步,非阻塞风格。大多数的现代操作系统提供了基于事件通知的子系统。例如,一个正常的socket上的`read`调用会发生阻塞,直到发送方把信息发送过来。但是,实际上程序可以请求操作系统监视socket事件的到来,并将这个事件通知放到事件队列中。这样,程序就可以很简单地检查事件是否到来(可能此时正在使用cpu做数值处理的运算),并及时地获取数据。说libuv是异步的,是因为程序可以在一头表达对某一事件的兴趣,并在另一头获取到数据(对于时间或是空间来说)。它是非阻塞是因为应用程序无需在请求数据后等待,可以自由地做其他的事。libuv的事件循环方式很好地与该模型匹配, 因为操作系统事件可以视为另外一种libuv事件. 非阻塞方式可以保证在其他事件到来时被尽快处理(当然还要考虑硬件的能力)。 28 | 29 | ##### Note 30 | >我们不需要关心I/O在后台是如何工作的,但是由于我们的计算机硬件的工作方式,线程是处理器最基本的执行单元,libuv和操作系统通常会运行后台/工作者线程, 或者采用非阻塞方式来轮流执行任务。 31 | 32 | Bert Belder,一个libuv的核心开发者,通过一个短视频向我们解释了libuv的架构和它的后台工作方式。如果你之前没有接触过类似libuv,libev,这个视频会非常有用。视频的网址是https://youtu.be/nGn60vDSxQ4 。 33 | 34 | 包含了libuv的event-loop的更多详细信息的[文档](http://docs.libuv.org/en/v1.x/design.html#the-i-o-loop)。 35 | 36 | ## HELLO WORLD 37 | 38 | 让我们开始写第一个libuv程序吧!它什么都没做,只是开启了一个loop,然后很快地退出了。 39 | 40 | #### helloworld/main.c 41 | 42 | ```c 43 | #include 44 | #include 45 | #include 46 | 47 | int main() { 48 | uv_loop_t *loop = malloc(sizeof(uv_loop_t)); 49 | uv_loop_init(loop); 50 | 51 | printf("Now quitting.\n"); 52 | uv_run(loop, UV_RUN_DEFAULT); 53 | 54 | uv_loop_close(loop); 55 | free(loop); 56 | return 0; 57 | } 58 | ``` 59 | 60 | 这个程序会很快就退出了,因为没有可以很处理的事件。我们可以使用各种API函数来告诉event-loop我们要监视的事件。 61 | 62 | 从libuv的1.0版本开始,用户就可以在使用`uv_loop_init`初始化loop之前,给其分配相应的内存。这就允许你植入自定义的内存管理方法。记住要使用`uv_loop_close(uv_loop_t *)`关闭loop,然后再回收内存空间。在例子中,程序退出的时候会关闭loop,系统也会自动回收内存。对于长时间运行的程序来说,合理释放内存很重要。 63 | 64 | ### Default loop 65 | 66 | 可以使用`uv_default_loop`获取libuv提供的默认loop。如果你只需要一个loop的话,可以使用这个。 67 | 68 | ##### Note 69 | 70 | >nodejs中使用了默认的loop作为自己的主loop。如果你在编写nodejs的绑定,你应该注意一下。 71 | 72 | ## Error handling 73 | 74 | 初始化函数或者同步执行的函数,会在执行失败后返回代表错误的负数。但是对于异步执行的函数,会在执行失败的时候,给它们的回调函数传递一个状态参数。错误信息被定义为`UV_E*`[常量](http://docs.libuv.org/en/v1.x/errors.html#error-constants)。 75 | 76 | 你可以使用`uv_strerror(int)`和`uv_err_name(int)`分别获取`const char *`格式的错误信息和错误名字。 77 | 78 | I/O函数的回调函数(例如文件和socket等)会被传递一个`nread`参数。如果`nread`小于0,就代表出现了错误(当然,UV_EOF是读取到文件末端的错误,你要特殊处理)。 79 | 80 | ##Handles and Requests 81 | 82 | libuv的工作建立在用户表达对特定事件的兴趣。这通常通过创造对应I/O设备,定时器,进程等的handle来实现。handle是不透明的数据结构,其中对应的类型`uv_TYPE_t`中的type指定了handle的使用目的。 83 | 84 | #### libuv watchers 85 | 86 | ```c 87 | /* Handle types. */ 88 | typedef struct uv_loop_s uv_loop_t; 89 | typedef struct uv_handle_s uv_handle_t; 90 | typedef struct uv_stream_s uv_stream_t; 91 | typedef struct uv_tcp_s uv_tcp_t; 92 | typedef struct uv_udp_s uv_udp_t; 93 | typedef struct uv_pipe_s uv_pipe_t; 94 | typedef struct uv_tty_s uv_tty_t; 95 | typedef struct uv_poll_s uv_poll_t; 96 | typedef struct uv_timer_s uv_timer_t; 97 | typedef struct uv_prepare_s uv_prepare_t; 98 | typedef struct uv_check_s uv_check_t; 99 | typedef struct uv_idle_s uv_idle_t; 100 | typedef struct uv_async_s uv_async_t; 101 | typedef struct uv_process_s uv_process_t; 102 | typedef struct uv_fs_event_s uv_fs_event_t; 103 | typedef struct uv_fs_poll_s uv_fs_poll_t; 104 | typedef struct uv_signal_s uv_signal_t; 105 | 106 | /* Request types. */ 107 | typedef struct uv_req_s uv_req_t; 108 | typedef struct uv_getaddrinfo_s uv_getaddrinfo_t; 109 | typedef struct uv_getnameinfo_s uv_getnameinfo_t; 110 | typedef struct uv_shutdown_s uv_shutdown_t; 111 | typedef struct uv_write_s uv_write_t; 112 | typedef struct uv_connect_s uv_connect_t; 113 | typedef struct uv_udp_send_s uv_udp_send_t; 114 | typedef struct uv_fs_s uv_fs_t; 115 | typedef struct uv_work_s uv_work_t; 116 | 117 | /* None of the above. */ 118 | typedef struct uv_cpu_info_s uv_cpu_info_t; 119 | typedef struct uv_interface_address_s uv_interface_address_t; 120 | typedef struct uv_dirent_s uv_dirent_t; 121 | ``` 122 | 123 | handle代表了持久性对象。在异步的操作中,相应的handle上有许多与之关联的request。request是短暂性对象(通常只维持在一个回调函数的时间),通常对映着handle上的一个I/O操作。Requests用来在初始函数和回调函数之间,传递上下文。例如uv_udp_t代表了一个udp的socket,然而,对于每一个向socket的写入的完成后,都会向回调函数传递一个`uv_udp_send_t`。 124 | 125 | handle可以通过下面的函数设置: 126 | 127 | ```c 128 | uv_TYPE_init(uv_loop_t *, uv_TYPE_t *) 129 | ``` 130 | 131 | 回调函数是libuv所关注的事件发生后,所调用的函数。应用程序的特定逻辑会在回调函数中实现。例如,一个IO监视器的回调函数会接收到从文件读取到的数据,一个定时器的回调函数会在超时后被触发等等。 132 | 133 | ### Idling 134 | 135 | 下面有一个使用空转handle的例子。回调函数在每一个循环中都会被调用。在Utilities这部分会讲到一些空转handle的使用场景。现在让我们使用一个空转监视器,然后来观察它的生命周期,接着看`uv_run`调用会造成阻塞。当达到事先规定好的计数后,空转监视器会退出。因为`uv_run`已经找不到活着的事件监视器了,所以`uv_run()`也退出。 136 | 137 | #### idle-basic/main.c 138 | 139 | ```c 140 | #include 141 | #include 142 | 143 | int64_t counter = 0; 144 | 145 | void wait_for_a_while(uv_idle_t* handle) { 146 | counter++; 147 | 148 | if (counter >= 10e6) 149 | uv_idle_stop(handle); 150 | } 151 | 152 | int main() { 153 | uv_idle_t idler; 154 | 155 | uv_idle_init(uv_default_loop(), &idler); 156 | uv_idle_start(&idler, wait_for_a_while); 157 | 158 | printf("Idling...\n"); 159 | uv_run(uv_default_loop(), UV_RUN_DEFAULT); 160 | 161 | uv_loop_close(uv_default_loop()); 162 | return 0; 163 | } 164 | 165 | ``` 166 | 167 | ### Storing context 168 | 169 | 在基于回调函数的编程风格中,你可能会需要在调用处和回调函数之间,传递一些上下文等特定的应用信息。所有的handle和request都有一个`data`域,可以用来存储信息并传递。这是一个c语言库中很常见的模式。即使是`uv_loop_t`也有一个相似的`data`域。 170 | 171 | -------------------------------------------------------------------------------- /source/filesystem.md: -------------------------------------------------------------------------------- 1 | # Filesystem 2 | 3 | 简单的文件读写是通过```uv_fs_*```函数族和与之相关的```uv_fs_t```结构体完成的。 4 | 5 | #### note 6 | >libuv 提供的文件操作和 socket operations 并不相同。套接字操作使用了操作系统本身提供了非阻塞操作,而文件操作内部使用了阻塞函数,但是 libuv 是在线程池中调用这些函数,并在应用程序需要交互时通知在事件循环中注册的监视器。 7 | 8 | 所有的文件操作函数都有两种形式 - 同步**(synchronous)** 和 异步**( asynchronous)**。 9 | 10 | 同步方式如果没有指定回调函数则会被自动调用( 并阻塞),函数的返回值是[libuv error code](http://docs.libuv.org/en/v1.x/guide/basics.html#libuv-error-handling) 。但以上通常只对同步调用有意义。而异步方式则会在传入回调函数时被调用, 并且返回 0。 11 | 12 | ## Reading/Writing files 13 | 14 | 15 | 文件描述符可以采用如下方式获得: 16 | 17 | ```c 18 | int uv_fs_open(uv_loop_t* loop, uv_fs_t* req, const char* path, int flags, int mode, uv_fs_cb cb) 19 | ``` 20 | 21 | 参数```flags```与```mode```和标准的 Unix flags 相同。libuv 会小心地处理 Windows 环境下的相关标志位(flags)的转换, 所以编写跨平台程序时你不用担心不同平台上文件打开的标志位不同。 22 | 23 | 关闭文件描述符可以使用: 24 | 25 | ```c 26 | int uv_fs_close(uv_loop_t* loop, uv_fs_t* req, uv_file file, uv_fs_cb cb) 27 | ``` 28 | 29 | 文件系统的回调函数有如下的形式: 30 | 31 | ```c 32 | void callback(uv_fs_t* req); 33 | ``` 34 | 35 | 让我们看一下一个简单的```cat```命令的实现。我们通过当文件被打开时注册一个回调函数来开始: 36 | 37 | #### uvcat/main.c - opening a file 38 | 39 | ```c 40 | void on_open(uv_fs_t *req) { 41 | // The request passed to the callback is the same as the one the call setup 42 | // function was passed. 43 | assert(req == &open_req); 44 | if (req->result >= 0) { 45 | iov = uv_buf_init(buffer, sizeof(buffer)); 46 | uv_fs_read(uv_default_loop(), &read_req, req->result, 47 | &iov, 1, -1, on_read); 48 | } 49 | else { 50 | fprintf(stderr, "error opening file: %s\n", uv_strerror((int)req->result)); 51 | } 52 | } 53 | ``` 54 | 55 | `uv_fs_t`的`result`域保存了`uv_fs_open`回调函数**打开的文件描述符**。如果文件被正确地打开,我们可以开始读取了。 56 | 57 | #### uvcat/main.c - read callback 58 | 59 | ```c 60 | void on_read(uv_fs_t *req) { 61 | if (req->result < 0) { 62 | fprintf(stderr, "Read error: %s\n", uv_strerror(req->result)); 63 | } 64 | else if (req->result == 0) { 65 | uv_fs_t close_req; 66 | // synchronous 67 | uv_fs_close(uv_default_loop(), &close_req, open_req.result, NULL); 68 | } 69 | else if (req->result > 0) { 70 | iov.len = req->result; 71 | uv_fs_write(uv_default_loop(), &write_req, 1, &iov, 1, -1, on_write); 72 | } 73 | } 74 | ``` 75 | 76 | 在调用读取函数的时候,你必须传递一个已经初始化的缓冲区,在```on_read()```被触发后,缓冲区被写入数据。```uv_fs_*```系列的函数是和POSIX的函数对应的,所以当读到文件的末尾时(EOF),result返回0。在使用streams或者pipe的情况下,使用的是libuv自定义的```UV_EOF```。 77 | 78 | 现在你看到类似的异步编程的模式。但是```uv_fs_close()```是同步的。一般来说,一次性的,开始的或者关闭的部分,都是同步的,因为我们一般关心的主要是任务和多路I/O的快速I/O。所以在这些对性能微不足道的地方,都是使用同步的,这样代码还会简单一些。 79 | 80 | 文件系统的写入使用 ```uv_fs_write()```,当写入完成时会触发回调函数,在这个例子中回调函数会触发下一次的读取。 81 | #### uvcat/main.c - write callback 82 | 83 | ```c 84 | void on_write(uv_fs_t *req) { 85 | if (req->result < 0) { 86 | fprintf(stderr, "Write error: %s\n", uv_strerror((int)req->result)); 87 | } 88 | else { 89 | uv_fs_read(uv_default_loop(), &read_req, open_req.result, &iov, 1, -1, on_read); 90 | } 91 | } 92 | ``` 93 | 94 | ##### Warning 95 | >由于文件系统和磁盘的调度策略,写入成功的数据不一定就存在磁盘上。 96 | 97 | 我们开始在main中推动多米诺骨牌: 98 | 99 | #### uvcat/main.c 100 | 101 | ```c 102 | int main(int argc, char **argv) { 103 | uv_fs_open(uv_default_loop(), &open_req, argv[1], O_RDONLY, 0, on_open); 104 | uv_run(uv_default_loop(), UV_RUN_DEFAULT); 105 | 106 | uv_fs_req_cleanup(&open_req); 107 | uv_fs_req_cleanup(&read_req); 108 | uv_fs_req_cleanup(&write_req); 109 | return 0; 110 | } 111 | ``` 112 | 113 | ##### Warning 114 | >函数uv_fs_req_cleanup()在文件系统操作结束后必须要被调用,用来回收在读写中分配的内存。 115 | 116 | ##Filesystem operations 117 | 118 | 119 | 所有像 ``unlink``, ``rmdir``, ``stat`` 这样的标准文件操作都是支持异步的,并且使用方法和上述类似。下面的各个函数的使用方法和read/write/open类似,在``uv_fs_t.result``中保存返回值。所有的函数如下所示: 120 | (译者注:返回的result值,<0表示出错,其他值表示成功。但>=0的值在不同的函数中表示的意义不一样,比如在```uv_fs_read```或者```uv_fs_write```中,它代表读取或写入的数据总量,但在```uv_fs_open```中表示打开的文件描述符。) 121 | 122 | ```c 123 | UV_EXTERN int uv_fs_close(uv_loop_t* loop, 124 | uv_fs_t* req, 125 | uv_file file, 126 | uv_fs_cb cb); 127 | UV_EXTERN int uv_fs_open(uv_loop_t* loop, 128 | uv_fs_t* req, 129 | const char* path, 130 | int flags, 131 | int mode, 132 | uv_fs_cb cb); 133 | UV_EXTERN int uv_fs_read(uv_loop_t* loop, 134 | uv_fs_t* req, 135 | uv_file file, 136 | const uv_buf_t bufs[], 137 | unsigned int nbufs, 138 | int64_t offset, 139 | uv_fs_cb cb); 140 | UV_EXTERN int uv_fs_unlink(uv_loop_t* loop, 141 | uv_fs_t* req, 142 | const char* path, 143 | uv_fs_cb cb); 144 | UV_EXTERN int uv_fs_write(uv_loop_t* loop, 145 | uv_fs_t* req, 146 | uv_file file, 147 | const uv_buf_t bufs[], 148 | unsigned int nbufs, 149 | int64_t offset, 150 | uv_fs_cb cb); 151 | UV_EXTERN int uv_fs_mkdir(uv_loop_t* loop, 152 | uv_fs_t* req, 153 | const char* path, 154 | int mode, 155 | uv_fs_cb cb); 156 | UV_EXTERN int uv_fs_mkdtemp(uv_loop_t* loop, 157 | uv_fs_t* req, 158 | const char* tpl, 159 | uv_fs_cb cb); 160 | UV_EXTERN int uv_fs_rmdir(uv_loop_t* loop, 161 | uv_fs_t* req, 162 | const char* path, 163 | uv_fs_cb cb); 164 | UV_EXTERN int uv_fs_scandir(uv_loop_t* loop, 165 | uv_fs_t* req, 166 | const char* path, 167 | int flags, 168 | uv_fs_cb cb); 169 | UV_EXTERN int uv_fs_scandir_next(uv_fs_t* req, 170 | uv_dirent_t* ent); 171 | UV_EXTERN int uv_fs_stat(uv_loop_t* loop, 172 | uv_fs_t* req, 173 | const char* path, 174 | uv_fs_cb cb); 175 | UV_EXTERN int uv_fs_fstat(uv_loop_t* loop, 176 | uv_fs_t* req, 177 | uv_file file, 178 | uv_fs_cb cb); 179 | UV_EXTERN int uv_fs_rename(uv_loop_t* loop, 180 | uv_fs_t* req, 181 | const char* path, 182 | const char* new_path, 183 | uv_fs_cb cb); 184 | UV_EXTERN int uv_fs_fsync(uv_loop_t* loop, 185 | uv_fs_t* req, 186 | uv_file file, 187 | uv_fs_cb cb); 188 | UV_EXTERN int uv_fs_fdatasync(uv_loop_t* loop, 189 | uv_fs_t* req, 190 | uv_file file, 191 | uv_fs_cb cb); 192 | UV_EXTERN int uv_fs_ftruncate(uv_loop_t* loop, 193 | uv_fs_t* req, 194 | uv_file file, 195 | int64_t offset, 196 | uv_fs_cb cb); 197 | UV_EXTERN int uv_fs_sendfile(uv_loop_t* loop, 198 | uv_fs_t* req, 199 | uv_file out_fd, 200 | uv_file in_fd, 201 | int64_t in_offset, 202 | size_t length, 203 | uv_fs_cb cb); 204 | UV_EXTERN int uv_fs_access(uv_loop_t* loop, 205 | uv_fs_t* req, 206 | const char* path, 207 | int mode, 208 | uv_fs_cb cb); 209 | UV_EXTERN int uv_fs_chmod(uv_loop_t* loop, 210 | uv_fs_t* req, 211 | const char* path, 212 | int mode, 213 | uv_fs_cb cb); 214 | UV_EXTERN int uv_fs_utime(uv_loop_t* loop, 215 | uv_fs_t* req, 216 | const char* path, 217 | double atime, 218 | double mtime, 219 | uv_fs_cb cb); 220 | UV_EXTERN int uv_fs_futime(uv_loop_t* loop, 221 | uv_fs_t* req, 222 | uv_file file, 223 | double atime, 224 | double mtime, 225 | uv_fs_cb cb); 226 | UV_EXTERN int uv_fs_lstat(uv_loop_t* loop, 227 | uv_fs_t* req, 228 | const char* path, 229 | uv_fs_cb cb); 230 | UV_EXTERN int uv_fs_link(uv_loop_t* loop, 231 | uv_fs_t* req, 232 | const char* path, 233 | const char* new_path, 234 | uv_fs_cb cb); 235 | ``` 236 | 237 | ## Buffers and Streams 238 | 239 | 在libuv中,最基础的I/O操作是流stream(``uv_stream_t``)。TCP套接字,UDP套接字,管道对于文件I/O和IPC来说,都可以看成是流stream(``uv_stream_t``)的子类。 240 | 上面提到的各个流的子类都有各自的初始化函数,然后可以使用下面的函数操作: 241 | 242 | ```c 243 | int uv_read_start(uv_stream_t*, uv_alloc_cb alloc_cb, uv_read_cb read_cb); 244 | int uv_read_stop(uv_stream_t*); 245 | int uv_write(uv_write_t* req, uv_stream_t* handle, 246 | const uv_buf_t bufs[], unsigned int nbufs, uv_write_cb cb); 247 | ``` 248 | 249 | 可以看出,流操作要比上述的文件操作要简单一些,而且当``uv_read_start()``一旦被调用,libuv会保持从流中持续地读取数据,直到``uv_read_stop()``被调用。 250 | 数据的离散单元是buffer-``uv_buffer_t``。它包含了指向数据的开始地址的指针(``uv_buf_t.base``)和buffer的长度(``uv_buf_t.len``)这两个信息。``uv_buf_t``很轻量级,使用值传递。我们需要管理的只是实际的数据,即程序必须自己分配和回收内存。 251 | 252 | **ERROR:** 253 | 254 | THIS PROGRAM DOES NOT ALWAYS WORK, NEED SOMETHING BETTER 255 | 256 | 为了更好地演示流stream,我们将会使用``uv_pipe_t``。它可以将本地文件转换为流(stream)的形态。接下来的这个是使用libuv实现的,一个简单的tee工具(如果不是很了解,请看[维基百科](https://en.wikipedia.org/wiki/Tee_(command)))。所有的操作都是异步的,这也正是事件驱动I/O的威力所在。两个输出操作不会相互阻塞,但是我们也必须要注意,确保一块缓冲区不会在还没有写入之前,就提前被回收了。 257 | 258 | 这个程序执行命令如下 259 | 260 | ``` 261 | ./uvtee 262 | ``` 263 | 264 | 在使用pipe打开文件时,libuv会默认地以可读和可写的方式打开文件。 265 | 266 | #### uvtee/main.c - read on pipes 267 | 268 | ```c 269 | int main(int argc, char **argv) { 270 | loop = uv_default_loop(); 271 | 272 | uv_pipe_init(loop, &stdin_pipe, 0); 273 | uv_pipe_open(&stdin_pipe, 0); 274 | 275 | uv_pipe_init(loop, &stdout_pipe, 0); 276 | uv_pipe_open(&stdout_pipe, 1); 277 | 278 | uv_fs_t file_req; 279 | int fd = uv_fs_open(loop, &file_req, argv[1], O_CREAT | O_RDWR, 0644, NULL); 280 | uv_pipe_init(loop, &file_pipe, 0); 281 | uv_pipe_open(&file_pipe, fd); 282 | 283 | uv_read_start((uv_stream_t*)&stdin_pipe, alloc_buffer, read_stdin); 284 | 285 | uv_run(loop, UV_RUN_DEFAULT); 286 | return 0; 287 | } 288 | ``` 289 | 290 | 当需要使用具名管道的时候(**译注:匿名管道 是Unix最初的IPC形式,但是由于匿名管道的局限性,后来出现了具名管道 FIFO,这种管道由于可以在文件系统中创建一个名字,所以可以被没有亲缘关系的进程访问**),``uv_pipe_init()``的第三个参数应该被设置为1。这部分会在Process进程的这一章节说明。``uv_pipe_open()``函数把管道和文件描述符关联起来,在上面的代码中表示把管道``stdin_pipe``和标准输入关联起来(**译者注:``0``代表标准输入,``1``代表标准输出,``2``代表标准错误输出**)。 291 | 292 | 当调用``uv_read_start()``后,我们开始监听``stdin``,当需要新的缓冲区来存储数据时,调用alloc_buffer,在函数``read_stdin()``中可以定义缓冲区中的数据处理操作。 293 | 294 | #### uvtee/main.c - reading buffers 295 | 296 | ```c 297 | void alloc_buffer(uv_handle_t *handle, size_t suggested_size, uv_buf_t *buf) { 298 | *buf = uv_buf_init((char*) malloc(suggested_size), suggested_size); 299 | } 300 | 301 | void read_stdin(uv_stream_t *stream, ssize_t nread, const uv_buf_t *buf) { 302 | if (nread < 0){ 303 | if (nread == UV_EOF){ 304 | // end of file 305 | uv_close((uv_handle_t *)&stdin_pipe, NULL); 306 | uv_close((uv_handle_t *)&stdout_pipe, NULL); 307 | uv_close((uv_handle_t *)&file_pipe, NULL); 308 | } 309 | } else if (nread > 0) { 310 | write_data((uv_stream_t *)&stdout_pipe, nread, *buf, on_stdout_write); 311 | write_data((uv_stream_t *)&file_pipe, nread, *buf, on_file_write); 312 | } 313 | 314 | if (buf->base) 315 | free(buf->base); 316 | } 317 | ``` 318 | 319 | 标准的``malloc``是非常高效的方法,但是你依然可以使用其它的内存分配的策略。比如,nodejs使用自己的内存分配方法(```Smalloc```),它将buffer用v8的对象关联起来,具体的可以查看[nodejs的官方文档](https://nodejs.org/docs/v0.11.5/api/smalloc.html)。 320 | 321 | 当回调函数```read_stdin()```的nread参数小于0时,表示错误发生了。其中一种可能的错误是EOF(**读到文件的尾部**),这时我们可以使用函数```uv_close()```关闭流了。除此之外,当nread大于0时,nread代表我们可以向输出流中写入的字节数目。最后注意,缓冲区要由我们手动回收。 322 | 323 | 当分配函数```alloc_buf()```返回一个长度为0的缓冲区时,代表它分配内存失败。在这种情况下,读取的回调函数会被错误```UV_ENOBUFS```唤醒。libuv同时也会继续尝试从流中读取数据,所以如果你想要停止的话,必须明确地调用```uv_close()```. 324 | 325 | 当nread为0时,代表已经没有可读的了,大多数的程序会自动忽略这个。 326 | 327 | #### uvtee/main.c - Write to pipe 328 | 329 | ```c 330 | typedef struct { 331 | uv_write_t req; 332 | uv_buf_t buf; 333 | } write_req_t; 334 | 335 | void free_write_req(uv_write_t *req) { 336 | write_req_t *wr = (write_req_t*) req; 337 | free(wr->buf.base); 338 | free(wr); 339 | } 340 | 341 | void on_stdout_write(uv_write_t *req, int status) { 342 | free_write_req(req); 343 | } 344 | 345 | void on_file_write(uv_write_t *req, int status) { 346 | free_write_req(req); 347 | } 348 | 349 | void write_data(uv_stream_t *dest, size_t size, uv_buf_t buf, uv_write_cb cb) { 350 | write_req_t *req = (write_req_t*) malloc(sizeof(write_req_t)); 351 | req->buf = uv_buf_init((char*) malloc(size), size); 352 | memcpy(req->buf.base, buf.base, size); 353 | uv_write((uv_write_t*) req, (uv_stream_t*)dest, &req->buf, 1, cb); 354 | } 355 | ``` 356 | 357 | `write_data()`开辟了一块地址空间存储从缓冲区读取出来的数据。这块缓存不会被释放,直到与``uv_write()``绑定的回调函数执行。为了实现它,我们用结构体``write_req_t``包裹一个write request和一个buffer,然后在回调函数中展开它。因为我们复制了一份缓存,所以我们可以在两个``write_data()``中独立释放两个缓存。 我们之所以这样做是因为,两个调用`write_data()`是相互独立的。为了保证它们不会因为读取速度的原因,由于共享一片缓冲区而损失掉独立性,所以才开辟了新的两块区域。当然这只是一个简单的例子,你可以使用更聪明的内存管理方法来实现它,比如引用计数或者缓冲区池等。 358 | 359 | 360 | ##### WARNING 361 | >你的程序在被其他的程序调用的过程中,有意无意地会向pipe写入数据,这样的话它会很容易被信号SIGPIPE终止掉,你最好在初始化程序的时候加入这句: 362 | >`signal(SIGPIPE, SIG_IGN)`。 363 | 364 | 365 | ## File change events 366 | 367 | 所有的现代操作系统都会提供相应的API来监视文件和文件夹的变化(**如Linux的inotify,Darwin的FSEvents,BSD的kqueue,Windows的ReadDirectoryChangesW, Solaris的event ports**)。libuv同样包括了这样的文件监视库。这是libuv中很不协调的部分,因为在跨平台的前提上,实现这个功能很难。为了更好地说明,我们现在来写一个监视文件变化的命令: 368 | 369 | ``` 370 | ./onchange [file2] ... 371 | ``` 372 | 实现这个监视器,要从```uv_fs_event_init()```开始: 373 | 374 | #### onchange/main.c - The setup 375 | ```c 376 | int main(int argc, char **argv) { 377 | if (argc <= 2) { 378 | fprintf(stderr, "Usage: %s [file2 ...]\n", argv[0]); 379 | return 1; 380 | } 381 | 382 | loop = uv_default_loop(); 383 | command = argv[1]; 384 | 385 | while (argc-- > 2) { 386 | fprintf(stderr, "Adding watch on %s\n", argv[argc]); 387 | uv_fs_event_t *fs_event_req = malloc(sizeof(uv_fs_event_t)); 388 | uv_fs_event_init(loop, fs_event_req); 389 | // The recursive flag watches subdirectories too. 390 | uv_fs_event_start(fs_event_req, run_command, argv[argc], UV_FS_EVENT_RECURSIVE); 391 | } 392 | 393 | return uv_run(loop, UV_RUN_DEFAULT); 394 | } 395 | ``` 396 | 397 | 函数```uv_fs_event_start()```的第三个参数是要监视的文件或文件夹。最后一个参数,```flags```,可以是: 398 | 399 | ``` 400 | UV_FS_EVENT_WATCH_ENTRY = 1, 401 | UV_FS_EVENT_STAT = 2, 402 | UV_FS_EVENT_RECURSIVE = 4 403 | ``` 404 | 405 | `UV_FS_EVENT_WATCH_ENTRY`和`UV_FS_EVENT_STAT`不做任何事情(至少目前是这样),`UV_FS_EVENT_RECURSIVE`可以在支持的系统平台上递归地监视子文件夹。 406 | 在回调函数`run_command()`中,接收的参数如下: 407 | >1.`uv_fs_event_t *handle`-句柄。里面的path保存了发生改变的文件的地址。 408 | >2.`const char *filename`-如果目录被监视,它代表发生改变的文件名。只在Linux和Windows上不为null,在其他平台上可能为null。 409 | >3.`int flags` -`UV_RENAME`名字改变,`UV_CHANGE`内容改变之一,或者他们两者的按位或的结果(`|`)。 410 | >4.`int status`-当前为0。 411 | 412 | 在我们的例子中,只是简单地打印参数和调用`system()`运行command. 413 | 414 | #### onchange/main.c - file change notification callback 415 | ```c 416 | void run_command(uv_fs_event_t *handle, const char *filename, int events, int status) { 417 | char path[1024]; 418 | size_t size = 1023; 419 | // Does not handle error if path is longer than 1023. 420 | uv_fs_event_getpath(handle, path, &size); 421 | path[size] = '\0'; 422 | 423 | fprintf(stderr, "Change detected in %s: ", path); 424 | if (events & UV_RENAME) 425 | fprintf(stderr, "renamed"); 426 | if (events & UV_CHANGE) 427 | fprintf(stderr, "changed"); 428 | 429 | fprintf(stderr, " %s\n", filename ? filename : ""); 430 | system(command); 431 | } 432 | ``` 433 | 434 | ---- 435 | 436 | 437 | -------------------------------------------------------------------------------- /source/introduction.md: -------------------------------------------------------------------------------- 1 | # Introduction 2 | 3 | 本书由很多的libuv教程组成,libuv是一个高性能的,事件驱动的I/O库,并且提供了跨平台(如windows, linux)的API。 4 | 5 | 本书会涵盖libuv的主要部分,但是不会详细地讲解每一个函数和数据结构。[官方文档](http://docs.libuv.org/en/v1.x/)中可以查阅到完整的内容。 6 | 7 | 本书依然在不断完善中,所以有些章节会不完整,但我希望你能喜欢它。 8 | 9 | ## Who this book is for 10 | 11 | 如果你正在读此书,你或许是: 12 | 13 | >1. 系统程序员,会编写一些底层的程序,例如守护进程或者网络服务器/客户端。你也许发现了event-loop很适合于你的应用场景,然后你决定使用libuv。 14 | >2. 一个node.js的模块开发人员,决定使用C/C++封装系统平台某些同步或者异步API,并将其暴露给Javascript。你可以在node.js中只使用libuv。但你也需要参考其他资源,因为本书并没有包括v8/node.js相关的内容。 15 | 16 | 本书假设你对c语言有一定的了解。 17 | 18 | ## Background 19 | 20 | [node.js](https://nodejs.org/en/)最初开始于2009年,是一个可以让Javascript代码离开浏览器的执行环境也可以执行的项目。 node.js使用了Google的V8解析引擎和Marc Lehmann的libev。Node.js将事件驱动的I/O模型与适合该模型的编程语言(Javascript)融合在了一起。随着node.js的日益流行,node.js需要同时支持windows, 但是libev只能在Unix环境下运行。Windows 平台上与kqueue(FreeBSD)或者(e)poll(Linux)等内核事件通知相应的机制是IOCP。libuv提供了一个跨平台的抽象,由平台决定使用libev或IOCP。在node-v0.9.0版本中,libuv移除了libev的内容。 21 | 22 | 随着libuv的日益成熟,它成为了拥有卓越性能的系统编程库。除了node.js以外,包括Mozilla的[Rust](http://rust-lang.org)编程语言,和许多的语言都开始使用libuv。 23 | 24 | 本书基于libuv的v1.3.0。 25 | 26 | ## Code 27 | 28 | 本书中的实例代码都可以在[Github](https://github.com/nikhilm/uvbook/tree/master/code)上找到。 29 | -------------------------------------------------------------------------------- /source/networking.md: -------------------------------------------------------------------------------- 1 | # Networking 2 | 3 | 在 libuv 中,网络编程与直接使用 BSD socket 区别不大,有些地方还更简单,概念保持不变的同时,libuv 上所有接口都是非阻塞的。它还提供了很多工具函数,抽象了恼人、啰嗦的底层任务,如使用 BSD socket 结构体设置 socket 、DNS 查找以及调整各种 socket 参数。 4 | 5 | 在网络I/O中会使用到```uv_tcp_t```和```uv_udp_t```。 6 | 7 | ##### note 8 | >本章中的代码片段仅用于展示 libuv API ,并不是优质代码的范例,常有内存泄露和未关闭的连接。 9 | 10 | ## TCP 11 | TCP是面向连接的,字节流协议,因此基于libuv的stream实现。 12 | 13 | #### server 14 | 服务器端的建立流程如下: 15 | 16 | 1.```uv_tcp_init```建立tcp句柄。 17 | 2.```uv_tcp_bind```绑定。 18 | 3.```uv_listen```建立监听,当有新的连接到来时,激活调用回调函数。 19 | 4.```uv_accept```接收链接。 20 | 5.使用stream操作来和客户端通信。 21 | 22 | #### tcp-echo-server/main.c - The listen socket 23 | ```c 24 | int main() { 25 | loop = uv_default_loop(); 26 | 27 | uv_tcp_t server; 28 | uv_tcp_init(loop, &server); 29 | 30 | uv_ip4_addr("0.0.0.0", DEFAULT_PORT, &addr); 31 | 32 | uv_tcp_bind(&server, (const struct sockaddr*)&addr, 0); 33 | int r = uv_listen((uv_stream_t*) &server, DEFAULT_BACKLOG, on_new_connection); 34 | if (r) { 35 | fprintf(stderr, "Listen error %s\n", uv_strerror(r)); 36 | return 1; 37 | } 38 | return uv_run(loop, UV_RUN_DEFAULT); 39 | } 40 | ``` 41 | 42 | 你可以调用```uv_ip4_addr()```函数来将ip地址和端口号转换为sockaddr_in结构,这样就可以被BSD的socket使用了。要想完成逆转换的话可以调用```uv_ip4_name()```。 43 | ##### note 44 | >对应ipv6有类似的uv_ip6_* 45 | 46 | 大多数的设置函数是同步的,因为它们毕竟不是io操作。到了```uv_listen```这句,我们再次回到回调函数的风格上来。第二个参数是待处理的连接请求队列-最大长度的请求连接队列。 47 | 48 | 当客户端开始建立连接的时候,回调函数```on_new_connection```需要使用```uv_accept```去建立一个与客户端socket通信的句柄。同时,我们也要开始从流中读取数据。 49 | 50 | #### tcp-echo-server/main.c - Accepting the client 51 | ```c 52 | void on_new_connection(uv_stream_t *server, int status) { 53 | if (status < 0) { 54 | fprintf(stderr, "New connection error %s\n", uv_strerror(status)); 55 | // error! 56 | return; 57 | } 58 | 59 | uv_tcp_t *client = (uv_tcp_t*) malloc(sizeof(uv_tcp_t)); 60 | uv_tcp_init(loop, client); 61 | if (uv_accept(server, (uv_stream_t*) client) == 0) { 62 | uv_read_start((uv_stream_t*) client, alloc_buffer, echo_read); 63 | } 64 | else { 65 | uv_close((uv_handle_t*) client, NULL); 66 | } 67 | } 68 | ``` 69 | 70 | 上述的函数集和stream的例子类似,在code文件夹中可以找到更多的例子。记得在socket不需要后,调用uv_close。如果你不需要接受连接,你甚至可以在uv_listen的回调函数中调用uv_close。 71 | 72 | #### client 73 | 当你在服务器端完成绑定/监听/接收的操作后,在客户端只要简单地调用```uv_tcp_connect```,它的回调函数和上面类似,具体例子如下: 74 | 75 | ```c 76 | uv_tcp_t* socket = (uv_tcp_t*)malloc(sizeof(uv_tcp_t)); 77 | uv_tcp_init(loop, socket); 78 | 79 | uv_connect_t* connect = (uv_connect_t*)malloc(sizeof(uv_connect_t)); 80 | 81 | struct sockaddr_in dest; 82 | uv_ip4_addr("127.0.0.1", 80, &dest); 83 | 84 | uv_tcp_connect(connect, socket, dest, on_connect); 85 | ``` 86 | 87 | 当建立连接后,回调函数```on_connect```会被调用。回调函数会接收到一个uv_connect_t结构的数据,它的```handle```指向通信的socket。 88 | 89 | ## UDP 90 | 用户数据报协议(User Datagram Protocol)提供无连接的,不可靠的网络通信。因此,libuv不会提供一个stream实现的形式,而是提供了一个```uv_udp_t```句柄(接收端),和一个```uv_udp_send_t```句柄(发送端),还有相关的函数。也就是说,实际的读写api与正常的流读取类似。下面的例子展示了一个从DCHP服务器获取ip的例子。 91 | 92 | ##### note 93 | >你必须以管理员的权限运行udp-dhcp,因为它的端口号低于1024 94 | 95 | #### udp-dhcp/main.c - Setup and send UDP packets 96 | ```c 97 | uv_loop_t *loop; 98 | uv_udp_t send_socket; 99 | uv_udp_t recv_socket; 100 | 101 | int main() { 102 | loop = uv_default_loop(); 103 | 104 | uv_udp_init(loop, &recv_socket); 105 | struct sockaddr_in recv_addr; 106 | uv_ip4_addr("0.0.0.0", 68, &recv_addr); 107 | uv_udp_bind(&recv_socket, (const struct sockaddr *)&recv_addr, UV_UDP_REUSEADDR); 108 | uv_udp_recv_start(&recv_socket, alloc_buffer, on_read); 109 | 110 | uv_udp_init(loop, &send_socket); 111 | struct sockaddr_in broadcast_addr; 112 | uv_ip4_addr("0.0.0.0", 0, &broadcast_addr); 113 | uv_udp_bind(&send_socket, (const struct sockaddr *)&broadcast_addr, 0); 114 | uv_udp_set_broadcast(&send_socket, 1); 115 | 116 | uv_udp_send_t send_req; 117 | uv_buf_t discover_msg = make_discover_msg(); 118 | 119 | struct sockaddr_in send_addr; 120 | uv_ip4_addr("255.255.255.255", 67, &send_addr); 121 | uv_udp_send(&send_req, &send_socket, &discover_msg, 1, (const struct sockaddr *)&send_addr, on_send); 122 | 123 | return uv_run(loop, UV_RUN_DEFAULT); 124 | } 125 | ``` 126 | 127 | ##### note 128 | >ip地址为0.0.0.0,用来绑定所有的接口。255.255.255.255是一个广播地址,这也意味着数据报将往所有的子网接口中发送。端口号为0代表着由操作系统随机分配一个端口。 129 | 130 | 首先,我们设置了一个用于接收socket绑定了全部网卡,端口号为68作为DHCP客户端,然后开始从中读取数据。它会接收所有来自DHCP服务器的返回数据。我们设置了```UV_UDP_REUSEADDR```标记,用来和其他共享端口的 DHCP客户端和平共处。接着,我们设置了一个类似的发送socket,然后使用```uv_udp_send```向DHCP服务器(在67端口)发送广播。 131 | 132 | 设置广播发送是非常必要的,否则你会接收到`EACCES`[错误](http://beej.us/guide/bgnet/output/html/multipage/advanced.html#broadcast)。和此前一样,如果在读写中出错,返回码<0。 133 | 134 | 因为UDP不会建立连接,因此回调函数会接收到关于发送者的额外的信息。 135 | 136 | 当没有可读数据后,nread等于0。如果`addr`是`null`,它代表了没有可读数据(回调函数不会做任何处理)。如果不为null,则说明了从addr中接收到一个空的数据报。如果flag为```UV_UDP_PARTIAL```,则代表了内存分配的空间不够存放接收到的数据了,在这种情形下,操作系统会丢弃存不下的数据。 137 | 138 | #### udp-dhcp/main.c - Reading packets 139 | ```c 140 | void on_read(uv_udp_t *req, ssize_t nread, const uv_buf_t *buf, const struct sockaddr *addr, unsigned flags) { 141 | if (nread < 0) { 142 | fprintf(stderr, "Read error %s\n", uv_err_name(nread)); 143 | uv_close((uv_handle_t*) req, NULL); 144 | free(buf->base); 145 | return; 146 | } 147 | 148 | char sender[17] = { 0 }; 149 | uv_ip4_name((const struct sockaddr_in*) addr, sender, 16); 150 | fprintf(stderr, "Recv from %s\n", sender); 151 | 152 | // ... DHCP specific code 153 | unsigned int *as_integer = (unsigned int*)buf->base; 154 | unsigned int ipbin = ntohl(as_integer[4]); 155 | unsigned char ip[4] = {0}; 156 | int i; 157 | for (i = 0; i < 4; i++) 158 | ip[i] = (ipbin >> i*8) & 0xff; 159 | fprintf(stderr, "Offered IP %d.%d.%d.%d\n", ip[3], ip[2], ip[1], ip[0]); 160 | 161 | free(buf->base); 162 | uv_udp_recv_stop(req); 163 | } 164 | ``` 165 | 166 | #### UDP Options 167 | 168 | 生存时间(Time-to-live) 169 | >可以通过`uv_udp_set_ttl`更改生存时间。 170 | 171 | 只允许IPV6协议栈 172 | >在调用`uv_udp_bind`时,设置`UV_UDP_IPV6ONLY`标示,可以强制只使用ipv6。 173 | 174 | 组播 175 | >socket也支持组播,可以这么使用: 176 | 177 | ```c 178 | UV_EXTERN int uv_udp_set_membership(uv_udp_t* handle, 179 | const char* multicast_addr, 180 | const char* interface_addr, 181 | uv_membership membership); 182 | ``` 183 | 184 | 其中`membership`可以为`UV_JOIN_GROUP`和`UV_LEAVE_GROUP`。 185 | 这里有一篇很好的关于组播的[文章](http://www.tldp.org/HOWTO/Multicast-HOWTO-2.html)。 186 | 可以使用`uv_udp_set_multicast_loop`修改本地的组播。 187 | 同样可以使用`uv_udp_set_multicast_ttl`修改组播数据报的生存时间。(设定生存时间可以防止数据报由于环路的原因,会出现无限循环的问题)。 188 | 189 | ## Querying DNS 190 | libuv提供了一个异步的DNS解决方案。它提供了自己的`getaddrinfo`。在回调函数中你可以像使用正常的socket操作一样。让我们来看一下例子: 191 | 192 | #### dns/main.c 193 | ```c 194 | int main() { 195 | loop = uv_default_loop(); 196 | 197 | struct addrinfo hints; 198 | hints.ai_family = PF_INET; 199 | hints.ai_socktype = SOCK_STREAM; 200 | hints.ai_protocol = IPPROTO_TCP; 201 | hints.ai_flags = 0; 202 | 203 | uv_getaddrinfo_t resolver; 204 | fprintf(stderr, "irc.freenode.net is... "); 205 | int r = uv_getaddrinfo(loop, &resolver, on_resolved, "irc.freenode.net", "6667", &hints); 206 | 207 | if (r) { 208 | fprintf(stderr, "getaddrinfo call error %s\n", uv_err_name(r)); 209 | return 1; 210 | } 211 | return uv_run(loop, UV_RUN_DEFAULT); 212 | } 213 | ``` 214 | 215 | 如果`uv_getaddrinfo`返回非零值,说明设置错误了,因此也不会激发回调函数。在函数返回后,所有的参数将会被回收和释放。主机地址,请求服务器地址,还有hints的结构都可以在[这里](http://nikhilm.github.io/uvbook/getaddrinfo)找到详细的说明。如果想使用同步请求,可以将回调函数设置为NULL。 216 | 217 | 在回调函数on_resolved中,你可以从`struct addrinfo(s)`链表中获取返回的IP,最后需要调用`uv_freeaddrinfo`回收掉链表。下面的例子演示了回调函数的内容。 218 | 219 | #### dns/main.c 220 | ```c 221 | void on_resolved(uv_getaddrinfo_t *resolver, int status, struct addrinfo *res) { 222 | if (status < 0) { 223 | fprintf(stderr, "getaddrinfo callback error %s\n", uv_err_name(status)); 224 | return; 225 | } 226 | 227 | char addr[17] = {'\0'}; 228 | uv_ip4_name((struct sockaddr_in*) res->ai_addr, addr, 16); 229 | fprintf(stderr, "%s\n", addr); 230 | 231 | uv_connect_t *connect_req = (uv_connect_t*) malloc(sizeof(uv_connect_t)); 232 | uv_tcp_t *socket = (uv_tcp_t*) malloc(sizeof(uv_tcp_t)); 233 | uv_tcp_init(loop, socket); 234 | 235 | uv_tcp_connect(connect_req, socket, (const struct sockaddr*) res->ai_addr, on_connect); 236 | 237 | uv_freeaddrinfo(res); 238 | } 239 | ``` 240 | 241 | libuv同样提供了DNS逆解析的函数[uv_getnameinfo](http://docs.libuv.org/en/v1.x/dns.html#c.uv_getnameinfo])。 242 | 243 | ## Network interfaces 244 | 245 | 可以调用`uv_interface_addresses`获得系统的网络接口信息。下面这个简单的例子打印出所有可以获取的信息。这在服务器开始准备绑定IP地址的时候很有用。 246 | 247 | #### interfaces/main.c 248 | 249 | ```c 250 | #include 251 | #include 252 | 253 | int main() { 254 | char buf[512]; 255 | uv_interface_address_t *info; 256 | int count, i; 257 | 258 | uv_interface_addresses(&info, &count); 259 | i = count; 260 | 261 | printf("Number of interfaces: %d\n", count); 262 | while (i--) { 263 | uv_interface_address_t interface = info[i]; 264 | 265 | printf("Name: %s\n", interface.name); 266 | printf("Internal? %s\n", interface.is_internal ? "Yes" : "No"); 267 | 268 | if (interface.address.address4.sin_family == AF_INET) { 269 | uv_ip4_name(&interface.address.address4, buf, sizeof(buf)); 270 | printf("IPv4 address: %s\n", buf); 271 | } 272 | else if (interface.address.address4.sin_family == AF_INET6) { 273 | uv_ip6_name(&interface.address.address6, buf, sizeof(buf)); 274 | printf("IPv6 address: %s\n", buf); 275 | } 276 | 277 | printf("\n"); 278 | } 279 | 280 | uv_free_interface_addresses(info, count); 281 | return 0; 282 | } 283 | ``` 284 | 285 | `is_internal`可以用来表示是否是内部的IP。由于一个物理接口会有多个IP地址,所以每一次while循环的时候都会打印一次。 286 | 287 | 288 | -------------------------------------------------------------------------------- /source/processes.md: -------------------------------------------------------------------------------- 1 | # Processes 2 | 3 | libuv提供了相当多的子进程管理函数,并且是跨平台的,还允许使用stream,或者说pipe完成进程间通信。 4 | 5 | 在UNIX中有一个共识,就是进程只做一件事,并把它做好。因此,进程通常通过创建子进程来完成不同的任务(例如,在shell中使用pipe)。 一个多进程的,通过消息通信的模型,总比多线程的,共享内存的模型要容易理解得多。 6 | 7 | 当前一个比较常见的反对事件驱动编程的原因在于,其不能很好地利用现代多核计算机的优势。一个多线程的程序,内核可以将线程调度到不同的cpu核心中执行,以提高性能。但是一个event-loop的程序只有一个线程。实际上,工作区可以被分配到多进程上,每一个进程执行一个event-loop,然后每一个进程被分配到不同的cpu核心中执行。 8 | 9 | ## Spawning child processes 10 | 11 | 一个最简单的用途是,你想要开始一个进程,然后知道它什么时候终止。需要使用`uv_spawn`完成任务: 12 | 13 | #### spawn/main.c 14 | 15 | ```c 16 | uv_loop_t *loop; 17 | uv_process_t child_req; 18 | uv_process_options_t options; 19 | int main() { 20 | loop = uv_default_loop(); 21 | 22 | char* args[3]; 23 | args[0] = "mkdir"; 24 | args[1] = "test-dir"; 25 | args[2] = NULL; 26 | 27 | options.exit_cb = on_exit; 28 | options.file = "mkdir"; 29 | options.args = args; 30 | 31 | int r; 32 | if ((r = uv_spawn(loop, &child_req, &options))) { 33 | fprintf(stderr, "%s\n", uv_strerror(r)); 34 | return 1; 35 | } else { 36 | fprintf(stderr, "Launched process with ID %d\n", child_req.pid); 37 | } 38 | 39 | return uv_run(loop, UV_RUN_DEFAULT); 40 | } 41 | ``` 42 | 43 | ##### Note 44 | 45 | >由于上述的options是全局变量,因此被初始化为0。如果你在局部变量中定义options,请记得将所有没用的域设为0 46 | 47 | ```c 48 | uv_process_options_t options = {0}; 49 | ``` 50 | 51 | `uv_process_t`只是作为句柄,所有的选择项都通过`uv_process_options_t`设置,为了简单地开始一个进程,你只需要设置file和args,file是要执行的程序,args是所需的参数(和c语言中main函数的传入参数类似)。因为`uv_spawn`在内部使用了[execvp](http://man7.org/linux/man-pages/man3/exec.3.html),所以不需要提供绝对地址。遵从惯例,**实际传入参数的数目要比需要的参数多一个,因为最后一个参数会被设为NULL**。 52 | 53 | 在函数`uv_spawn`被调用之后,`uv_process_t.pid`会包含子进程的id。 54 | 55 | 回调函数`on_exit()`会在被调用的时候,传入exit状态和导致exit的信号。 56 | 57 | #### spawn/main.c 58 | 59 | ```c 60 | void on_exit(uv_process_t *req, int64_t exit_status, int term_signal) { 61 | fprintf(stderr, "Process exited with status %" PRId64 ", signal %d\n", exit_status, term_signal); 62 | uv_close((uv_handle_t*) req, NULL); 63 | ``` 64 | 65 | 在进程关闭后,需要回收handler。 66 | 67 | ## Changing process parameters 68 | 69 | 在子进程开始执行前,你可以通过使用`uv_process_options_t`设置运行环境。 70 | 71 | ### Change execution directory 72 | 73 | 设置`uv_process_options_t.cwd`,更改相应的目录。 74 | 75 | ### Set environment variables 76 | 77 | `uv_process_options_t.env`的格式是以null为结尾的字符串数组,其中每一个字符串的形式都是`VAR=VALUE`。这些值用来设置进程的环境变量。如果子进程想要继承父进程的环境变量,就将`uv_process_options_t.env`设为null。 78 | 79 | ### Option flags 80 | 81 | 通过使用下面标识的按位或的值设置`uv_process_options_t.flags`的值,可以定义子进程的行为: 82 | 83 | >* `UV_PROCESS_SETUID`-将子进程的执行用户id(UID)设置为`uv_process_options_t.uid`中的值。 84 | * `UV_PROCESS_SETGID`-将子进程的执行组id(GID)设置为`uv_process_options_t.gid`中的值。 85 | 只有在unix系的操作系统中支持设置用户id和组id,在windows下设置会失败,`uv_spawn`会返回`UV_ENOTSUP`。 86 | * `UV_PROCESS_WINDOWS_VERBATIM_ARGUMENTS`-在windows上,`uv_process_options_t.args`参数不要用引号包裹。此标记对unix无效。 87 | * `UV_PROCESS_DETACHED`-在新会话(session)中启动子进程,这样子进程就可以在父进程退出后继续进行。请看下面的例子: 88 | 89 | ## Detaching processes 90 | 91 | 使用标识`UV_PROCESS_DETACHED`可以启动守护进程(daemon),或者是使得子进程从父进程中独立出来,这样父进程的退出就不会影响到它。 92 | 93 | #### detach/main.c 94 | 95 | ```c 96 | int main() { 97 | loop = uv_default_loop(); 98 | 99 | char* args[3]; 100 | args[0] = "sleep"; 101 | args[1] = "100"; 102 | args[2] = NULL; 103 | 104 | options.exit_cb = NULL; 105 | options.file = "sleep"; 106 | options.args = args; 107 | options.flags = UV_PROCESS_DETACHED; 108 | 109 | int r; 110 | if ((r = uv_spawn(loop, &child_req, &options))) { 111 | fprintf(stderr, "%s\n", uv_strerror(r)); 112 | return 1; 113 | } 114 | fprintf(stderr, "Launched sleep with PID %d\n", child_req.pid); 115 | uv_unref((uv_handle_t*) &child_req); 116 | 117 | return uv_run(loop, UV_RUN_DEFAULT); 118 | ``` 119 | 120 | 记住一点,就是handle会始终监视着子进程,所以你的程序不会退出。`uv_unref()`会解除handle。 121 | 122 | ## Sending signals to processes 123 | 124 | libuv打包了unix标准的`kill(2)`系统调用,并且在windows上实现了一个类似用法的调用,但要注意:所有的`SIGTERM`,`SIGINT`和`SIGKILL`都会导致进程的中断。`uv_kill`函数如下所示: 125 | 126 | ```c 127 | uv_err_t uv_kill(int pid, int signum); 128 | ``` 129 | 130 | 对于用libuv启动的进程,应该使用`uv_process_kill`终止,它会以`uv_process_t`作为第一个参数,而不是pid。当使用`uv_process_kill`后,记得使用`uv_close`关闭`uv_process_t`。 131 | 132 | ## Signals 133 | 134 | libuv对unix信号和一些[windows下类似的机制](http://docs.libuv.org/en/v1.x/signal.html#signal),做了很好的打包。 135 | 136 | 使用`uv_signal_init`初始化handle(`uv_signal_t `),然后将它与loop关联。为了使用handle监听特定的信号,使用`uv_signal_start()`函数。每一个handle只能与一个信号关联,后续的`uv_signal_start`会覆盖前面的关联。使用`uv_signal_stop`终止监听。下面的这个小例子展示了各种用法: 137 | 138 | #### signal/main.c 139 | 140 | ```c 141 | #include 142 | #include 143 | #include 144 | #include 145 | 146 | uv_loop_t* create_loop() 147 | { 148 | uv_loop_t *loop = malloc(sizeof(uv_loop_t)); 149 | if (loop) { 150 | uv_loop_init(loop); 151 | } 152 | return loop; 153 | } 154 | 155 | void signal_handler(uv_signal_t *handle, int signum) 156 | { 157 | printf("Signal received: %d\n", signum); 158 | uv_signal_stop(handle); 159 | } 160 | 161 | // two signal handlers in one loop 162 | void thread1_worker(void *userp) 163 | { 164 | uv_loop_t *loop1 = create_loop(); 165 | 166 | uv_signal_t sig1a, sig1b; 167 | uv_signal_init(loop1, &sig1a); 168 | uv_signal_start(&sig1a, signal_handler, SIGUSR1); 169 | 170 | uv_signal_init(loop1, &sig1b); 171 | uv_signal_start(&sig1b, signal_handler, SIGUSR1); 172 | 173 | uv_run(loop1, UV_RUN_DEFAULT); 174 | } 175 | 176 | // two signal handlers, each in its own loop 177 | void thread2_worker(void *userp) 178 | { 179 | uv_loop_t *loop2 = create_loop(); 180 | uv_loop_t *loop3 = create_loop(); 181 | 182 | uv_signal_t sig2; 183 | uv_signal_init(loop2, &sig2); 184 | uv_signal_start(&sig2, signal_handler, SIGUSR1); 185 | 186 | uv_signal_t sig3; 187 | uv_signal_init(loop3, &sig3); 188 | uv_signal_start(&sig3, signal_handler, SIGUSR1); 189 | 190 | while (uv_run(loop2, UV_RUN_NOWAIT) || uv_run(loop3, UV_RUN_NOWAIT)) { 191 | } 192 | } 193 | 194 | int main() 195 | { 196 | printf("PID %d\n", getpid()); 197 | 198 | uv_thread_t thread1, thread2; 199 | 200 | uv_thread_create(&thread1, thread1_worker, 0); 201 | uv_thread_create(&thread2, thread2_worker, 0); 202 | 203 | uv_thread_join(&thread1); 204 | uv_thread_join(&thread2); 205 | return 0; 206 | } 207 | ``` 208 | 209 | ##### Note 210 | >`uv_run(loop, UV_RUN_NOWAIT)`和`uv_run(loop, UV_RUN_ONCE)`非常像,因为它们都只处理一个事件。但是不同在于,UV_RUN_ONCE会在没有任务的时候阻塞,但是UV_RUN_NOWAIT会立刻返回。我们使用`NOWAIT`,这样才使得一个loop不会因为另外一个loop没有要处理的事件而挨饿。 211 | 212 | 当向进程发送`SIGUSR1`,你会发现signal_handler函数被激发了4次,每次都对应一个`uv_signal_t`。然后signal_handler调用uv_signal_stop终止了每一个`uv_signal_t`,最终程序退出。对每个handler函数来说,任务的分配很重要。一个使用了多个event-loop的服务器程序,只要简单地给每一个进程添加信号SIGINT监视器,就可以保证程序在中断退出前,数据能够安全地保存。 213 | 214 | ## Child Process I/O 215 | 216 | 一个正常的新产生的进程都有自己的一套文件描述符映射表,例如0,1,2分别对应`stdin`,`stdout`和`stderr`。有时候父进程想要将自己的文件描述符映射表分享给子进程。例如,你的程序启动了一个子命令,并且把所有的错误信息输出到log文件中,但是不能使用`stdout`。因此,你想要使得你的子进程和父进程一样,拥有`stderr`。在这种情形下,libuv提供了继承文件描述符的功能。在下面的例子中,我们会调用这么一个测试程序: 217 | 218 | #### proc-streams/test.c 219 | 220 | ```c 221 | #include 222 | 223 | int main() 224 | { 225 | fprintf(stderr, "This is stderr\n"); 226 | printf("This is stdout\n"); 227 | return 0; 228 | } 229 | ``` 230 | 231 | 实际的执行程序` proc-streams`在运行的时候,只向子进程分享`stderr`。使用`uv_process_options_t`的`stdio`域设置子进程的文件描述符。首先设置`stdio_count`,定义文件描述符的个数。`uv_process_options_t.stdio`是一个`uv_stdio_container_t`数组。定义如下: 232 | 233 | ```c 234 | typedef struct uv_stdio_container_s { 235 | uv_stdio_flags flags; 236 | 237 | union { 238 | uv_stream_t* stream; 239 | int fd; 240 | } data; 241 | } uv_stdio_container_t; 242 | ``` 243 | 244 | 上边的flag值可取多种。比如,如果你不打算使用,可以设置为`UV_IGNORE`。如果与stdio中对应的前三个文件描述符被标记为`UV_IGNORE`,那么它们会被重定向到`/dev/null`。 245 | 246 | 因为我们想要传递一个已经存在的文件描述符,所以使用`UV_INHERIT_FD`。因此,fd被设为stderr。 247 | 248 | #### proc-streams/main.c 249 | 250 | ```c 251 | int main() { 252 | loop = uv_default_loop(); 253 | 254 | /* ... */ 255 | 256 | options.stdio_count = 3; 257 | uv_stdio_container_t child_stdio[3]; 258 | child_stdio[0].flags = UV_IGNORE; 259 | child_stdio[1].flags = UV_IGNORE; 260 | child_stdio[2].flags = UV_INHERIT_FD; 261 | child_stdio[2].data.fd = 2; 262 | options.stdio = child_stdio; 263 | 264 | options.exit_cb = on_exit; 265 | options.file = args[0]; 266 | options.args = args; 267 | 268 | int r; 269 | if ((r = uv_spawn(loop, &child_req, &options))) { 270 | fprintf(stderr, "%s\n", uv_strerror(r)); 271 | return 1; 272 | } 273 | 274 | return uv_run(loop, UV_RUN_DEFAULT); 275 | } 276 | ``` 277 | 278 | 这时你启动proc-streams,也就是在main中产生一个执行test的子进程,你只会看到“This is stderr”。你可以试着设置stdout也继承父进程。 279 | 280 | 同样可以把上述方法用于流的重定向。比如,把flag设为`UV_INHERIT_STREAM`,然后再设置父进程中的`data.stream`,这时子进程只会把这个stream当成是标准的I/O。这可以用来实现,例如[CGI](https://en.wikipedia.org/wiki/Common_Gateway_Interface)。 281 | 282 | 一个简单的CGI脚本的例子如下: 283 | 284 | #### cgi/tick.c 285 | 286 | ```c 287 | #include 288 | #include 289 | 290 | int main() { 291 | int i; 292 | for (i = 0; i < 10; i++) { 293 | printf("tick\n"); 294 | fflush(stdout); 295 | sleep(1); 296 | } 297 | printf("BOOM!\n"); 298 | return 0; 299 | } 300 | ``` 301 | 302 | CGI服务器用到了这章和[网络](http://luohaha.github.io/Chinese-uvbook/source/networking.html)那章的知识,所以每一个client都会被发送10个tick,然后被中断连接。 303 | 304 | #### cgi/main.c 305 | 306 | ```c 307 | void on_new_connection(uv_stream_t *server, int status) { 308 | if (status == -1) { 309 | // error! 310 | return; 311 | } 312 | 313 | uv_tcp_t *client = (uv_tcp_t*) malloc(sizeof(uv_tcp_t)); 314 | uv_tcp_init(loop, client); 315 | if (uv_accept(server, (uv_stream_t*) client) == 0) { 316 | invoke_cgi_script(client); 317 | } 318 | else { 319 | uv_close((uv_handle_t*) client, NULL); 320 | } 321 | ``` 322 | 323 | 上述代码中,我们接受了连接,并把socket(流)传递给`invoke_cgi_script`。 324 | 325 | #### cgi/main.c 326 | 327 | ```c 328 | args[1] = NULL; 329 | 330 | /* ... finding the executable path and setting up arguments ... */ 331 | 332 | options.stdio_count = 3; 333 | uv_stdio_container_t child_stdio[3]; 334 | child_stdio[0].flags = UV_IGNORE; 335 | child_stdio[1].flags = UV_INHERIT_STREAM; 336 | child_stdio[1].data.stream = (uv_stream_t*) client; 337 | child_stdio[2].flags = UV_IGNORE; 338 | options.stdio = child_stdio; 339 | 340 | options.exit_cb = cleanup_handles; 341 | options.file = args[0]; 342 | options.args = args; 343 | 344 | // Set this so we can close the socket after the child process exits. 345 | child_req.data = (void*) client; 346 | int r; 347 | if ((r = uv_spawn(loop, &child_req, &options))) { 348 | fprintf(stderr, "%s\n", uv_strerror(r)); 349 | ``` 350 | 351 | cgi的`stdout`被绑定到socket上,所以无论tick脚本程序打印什么,都会发送到client端。通过使用进程,我们能够很好地处理读写并发操作,而且用起来也很方便。但是要记得这么做,是很浪费资源的。 352 | 353 | ## Pipes 354 | 355 | libuv的`uv_pipe_t`结构可能会让一些unix程序员产生困惑,因为它像魔术般变幻出`|`和[`pipe(7)`](http://man7.org/linux/man-pages/man7/pipe.7.html)。但这里的`uv_pipe_t`并不是IPC机制里的 匿名管道(在IPC里,pipe是 匿名管道,只允许父子进程之间通信。FIFO则允许没有亲戚关系的进程间通信,显然llibuv里的`uv_pipe_t`不是第一种)。`uv_pipe_t`背后有[unix本地socket](http://man7.org/linux/man-pages/man7/unix.7.html)或者[windows 具名管道](https://msdn.microsoft.com/en-us/library/windows/desktop/aa365590.aspx)的支持,可以实现多进程间的通信。下面会具体讨论。 356 | 357 | #### Parent-child IPC 358 | 359 | 父进程与子进程可以通过单工或者双工管道通信,获得管道可以通过设置`uv_stdio_container_t.flags`为`UV_CREATE_PIPE`,`UV_READABLE_PIPE`或者`UV_WRITABLE_PIPE`的按位或的值。上述的读/写标记是对于子进程而言的。 360 | 361 | #### Arbitrary process IPC 362 | 363 | 既然本地socket具有确定的名称,而且是以文件系统上的位置来标示的(例如,unix中socket是文件的一种存在形式),那么它就可以用来在不相关的进程间完成通信任务。被开源桌面环境使用的[`D-BUS`系统](http://www.freedesktop.org/wiki/Software/dbus/)也是使用了本地socket来作为事件通知的,例如,当消息来到,或者检测到硬件的时候,各种应用程序会被通知到。mysql服务器也运行着一个本地socket,等待客户端的访问。 364 | 365 | 当使用本地socket的时候,客户端/服务器模型通常和之前类似。在完成初始化后,发送和接受消息的方法和之前的tcp类似,接下来我们同样适用echo服务器的例子来说明。 366 | 367 | #### pipe-echo-server/main.c 368 | 369 | ```c 370 | int main() { 371 | loop = uv_default_loop(); 372 | 373 | uv_pipe_t server; 374 | uv_pipe_init(loop, &server, 0); 375 | 376 | signal(SIGINT, remove_sock); 377 | 378 | int r; 379 | if ((r = uv_pipe_bind(&server, "echo.sock"))) { 380 | fprintf(stderr, "Bind error %s\n", uv_err_name(r)); 381 | return 1; 382 | } 383 | if ((r = uv_listen((uv_stream_t*) &server, 128, on_new_connection))) { 384 | fprintf(stderr, "Listen error %s\n", uv_err_name(r)); 385 | return 2; 386 | } 387 | return uv_run(loop, UV_RUN_DEFAULT); 388 | } 389 | ``` 390 | 391 | 我们把socket命名为echo.sock,意味着它将会在本地文件夹中被创造。对于stream API来说,本地socekt表现得和tcp的socket差不多。你可以使用[socat](http://www.dest-unreach.org/socat/)测试一下服务器: 392 | 393 | ``` 394 | $ socat - /path/to/socket 395 | ``` 396 | 397 | 客户端如果想要和服务器端连接的话,应该使用: 398 | 399 | ```c 400 | void uv_pipe_connect(uv_connect_t *req, uv_pipe_t *handle, const char *name, uv_connect_cb cb); 401 | ``` 402 | 403 | 上述函数,name应该为echo.sock。 404 | 405 | #### Sending file descriptors over pipes 406 | 407 | 最酷的事情是本地socket可以传递文件描述符,也就是说进程间可以交换文件描述符。这样就允许进程将它们的I/O传递给其他进程。它的应用场景包括,负载均衡服务器,分派工作进程等,各种可以使得cpu使用最优化的应用。libuv当前只支持通过管道传输**TCP sockets或者其他的pipes**。 408 | 409 | 为了展示这个功能,我们将来实现一个由循环中的工人进程处理client端请求,的这么一个echo服务器程序。这个程序有一些复杂,在教程中只截取了部分的片段,为了更好地理解,我推荐你去读下完整的[代码](https://github.com/nikhilm/uvbook/tree/master/code/multi-echo-server)。 410 | 411 | 工人进程很简单,文件描述符将从主进程传递给它。 412 | 413 | #### multi-echo-server/worker.c 414 | 415 | ```c 416 | uv_loop_t *loop; 417 | uv_pipe_t queue; 418 | int main() { 419 | loop = uv_default_loop(); 420 | 421 | uv_pipe_init(loop, &queue, 1 /* ipc */); 422 | uv_pipe_open(&queue, 0); 423 | uv_read_start((uv_stream_t*)&queue, alloc_buffer, on_new_connection); 424 | return uv_run(loop, UV_RUN_DEFAULT); 425 | } 426 | ``` 427 | 428 | `queue`是另一端连接上主进程的管道,因此,文件描述符可以传送过来。在`uv_pipe_init`中将`ipc`参数设置为1很关键,因为它标明了这个管道将被用来做进程间通信。因为主进程需要把文件handle赋给了工人进程作为标准输入,因此我们使用`uv_pipe_open`把stdin作为pipe(别忘了,0代表stdin)。 429 | 430 | #### multi-echo-server/worker.c 431 | 432 | ```c 433 | void on_new_connection(uv_stream_t *q, ssize_t nread, const uv_buf_t *buf) { 434 | if (nread < 0) { 435 | if (nread != UV_EOF) 436 | fprintf(stderr, "Read error %s\n", uv_err_name(nread)); 437 | uv_close((uv_handle_t*) q, NULL); 438 | return; 439 | } 440 | 441 | uv_pipe_t *pipe = (uv_pipe_t*) q; 442 | if (!uv_pipe_pending_count(pipe)) { 443 | fprintf(stderr, "No pending count\n"); 444 | return; 445 | } 446 | 447 | uv_handle_type pending = uv_pipe_pending_type(pipe); 448 | assert(pending == UV_TCP); 449 | 450 | uv_tcp_t *client = (uv_tcp_t*) malloc(sizeof(uv_tcp_t)); 451 | uv_tcp_init(loop, client); 452 | if (uv_accept(q, (uv_stream_t*) client) == 0) { 453 | uv_os_fd_t fd; 454 | uv_fileno((const uv_handle_t*) client, &fd); 455 | fprintf(stderr, "Worker %d: Accepted fd %d\n", getpid(), fd); 456 | uv_read_start((uv_stream_t*) client, alloc_buffer, echo_read); 457 | } 458 | else { 459 | uv_close((uv_handle_t*) client, NULL); 460 | } 461 | } 462 | ``` 463 | 464 | 首先,我们调用`uv_pipe_pending_count`来确定从handle中可以读取出数据。如果你的程序能够处理不同类型的handle,这时`uv_pipe_pending_type`就可以用来决定当前的类型。虽然在这里使用`accept`看起来很怪,但实际上是讲得通的。`accept`最常见的用途是从其他的文件描述符(监听的socket)获取文件描述符(client端)。这从原理上说,和我们现在要做的是一样的:从queue中获取文件描述符(client)。接下来,worker可以执行标准的echo服务器的工作了。 465 | 466 | 我们再来看看主进程,观察如何启动worker来达到负载均衡。 467 | 468 | #### multi-echo-server/main.c 469 | 470 | ```c 471 | struct child_worker { 472 | uv_process_t req; 473 | uv_process_options_t options; 474 | uv_pipe_t pipe; 475 | } *workers; 476 | ``` 477 | 478 | `child_worker`结构包裹着进程,和连接主进程和各个独立进程的管道。 479 | 480 | #### multi-echo-server/main.c 481 | 482 | ```c 483 | void setup_workers() { 484 | round_robin_counter = 0; 485 | 486 | // ... 487 | 488 | // launch same number of workers as number of CPUs 489 | uv_cpu_info_t *info; 490 | int cpu_count; 491 | uv_cpu_info(&info, &cpu_count); 492 | uv_free_cpu_info(info, cpu_count); 493 | 494 | child_worker_count = cpu_count; 495 | 496 | workers = calloc(sizeof(struct child_worker), cpu_count); 497 | while (cpu_count--) { 498 | struct child_worker *worker = &workers[cpu_count]; 499 | uv_pipe_init(loop, &worker->pipe, 1); 500 | 501 | uv_stdio_container_t child_stdio[3]; 502 | child_stdio[0].flags = UV_CREATE_PIPE | UV_READABLE_PIPE; 503 | child_stdio[0].data.stream = (uv_stream_t*) &worker->pipe; 504 | child_stdio[1].flags = UV_IGNORE; 505 | child_stdio[2].flags = UV_INHERIT_FD; 506 | child_stdio[2].data.fd = 2; 507 | 508 | worker->options.stdio = child_stdio; 509 | worker->options.stdio_count = 3; 510 | 511 | worker->options.exit_cb = close_process_handle; 512 | worker->options.file = args[0]; 513 | worker->options.args = args; 514 | 515 | uv_spawn(loop, &worker->req, &worker->options); 516 | fprintf(stderr, "Started worker %d\n", worker->req.pid); 517 | } 518 | } 519 | ``` 520 | 521 | 首先,我们使用酷炫的`uv_cpu_info`函数获取到当前的cpu的核心个数,所以我们也能启动一样数目的worker进程。再次强调一下,务必将`uv_pipe_init`的ipc参数设置为1。接下来,我们指定子进程的`stdin`是一个可读的管道(从子进程的角度来说)。接下来的一切就很直观了,worker进程被启动,等待着文件描述符被写入到他们的标准输入中。 522 | 523 | 在主进程的`on_new_connection`中,我们接收了client端的socket,然后把它传递给worker环中的下一个可用的worker进程。 524 | 525 | #### multi-echo-server/main.c 526 | 527 | ```c 528 | void on_new_connection(uv_stream_t *server, int status) { 529 | if (status == -1) { 530 | // error! 531 | return; 532 | } 533 | 534 | uv_tcp_t *client = (uv_tcp_t*) malloc(sizeof(uv_tcp_t)); 535 | uv_tcp_init(loop, client); 536 | if (uv_accept(server, (uv_stream_t*) client) == 0) { 537 | uv_write_t *write_req = (uv_write_t*) malloc(sizeof(uv_write_t)); 538 | dummy_buf = uv_buf_init("a", 1); 539 | struct child_worker *worker = &workers[round_robin_counter]; 540 | uv_write2(write_req, (uv_stream_t*) &worker->pipe, &dummy_buf, 1, (uv_stream_t*) client, NULL); 541 | round_robin_counter = (round_robin_counter + 1) % child_worker_count; 542 | } 543 | else { 544 | uv_close((uv_handle_t*) client, NULL); 545 | } 546 | } 547 | ``` 548 | 549 | `uv_write2`能够在所有的情形上做了一个很好的抽象,我们只需要将client作为一个参数即可完成传输。现在,我们的多进程echo服务器已经可以运转起来啦。 550 | 551 | 感谢Kyle指出了`uv_write2`需要一个不为空的buffer。 552 | -------------------------------------------------------------------------------- /source/threads.md: -------------------------------------------------------------------------------- 1 | # Threads 2 | 等一下!为什么我们要聊线程?事件循环(event loop)不应该是用来做web编程的方法吗?(如果你对event loop, 不是很了解,可以看[这里](http://www.ruanyifeng.com/blog/2014/10/event-loop.html))。哦,不不。线程依旧是处理器完成任务的重要手段。线程因此有可能会派上用场,虽然会使得你不得不艰难地应对各种原始的同步问题。 3 | 4 | 线程会在内部使用,用来在执行系统调用时伪造异步的假象。libuv通过线程还可以使得程序异步地执行一个阻塞的任务。方法就是大量地生成新线程,然后收集线程执行返回的结果。 5 | 6 | 当下有两个占主导地位的线程库:windows下的线程实现和POSIX的[pthread](http://man7.org/linux/man-pages/man7/pthreads.7.html)。libuv的线程API与pthread的API在使用方法和语义上很接近。 7 | 8 | 值得注意的是,libuv的线程模块是自成一体的。比如,其他的功能模块都需要依赖于event loop和回调的原则,但是线程并不是这样。它们是不受约束的,会在需要的时候阻塞,通过返回值产生信号错误,还有像接下来的这个例子所演示的这样,不需要在event loop中执行。 9 | 10 | 因为线程API在不同的系统平台上,句法和语义表现得都不太相似,在支持程度上也各不相同。考虑到libuv的跨平台特性,libuv支持的线程API个数很有限。 11 | 12 | 最后要强调一句:只有一个主线程,主线程上只有一个event loop。不会有其他与主线程交互的线程了。(除非使用`uv_async_send`)。 13 | 14 | ## Core thread operations 15 | 16 | 下面这个例子不会很复杂,你可以使用`uv_thread_create()`开始一个线程,再使用`uv_thread_join()`等待其结束。 17 | 18 | #### thread-create/main.c 19 | 20 | ```c 21 | int main() { 22 | int tracklen = 10; 23 | uv_thread_t hare_id; 24 | uv_thread_t tortoise_id; 25 | uv_thread_create(&hare_id, hare, &tracklen); 26 | uv_thread_create(&tortoise_id, tortoise, &tracklen); 27 | 28 | uv_thread_join(&hare_id); 29 | uv_thread_join(&tortoise_id); 30 | return 0; 31 | } 32 | ``` 33 | 34 | ##### TIP 35 | >在Unix上``uv_thread_t``只是``pthread_t``的别名, 但是这只是一个具体实现,不要过度地依赖它,认为这永远是成立的。 36 | 37 | `uv_thread_create`的第二个参数指向了要执行的函数的地址。最后一个参数用来传递自定义的参数。最终,函数hare将在新的线程中执行,由操作系统调度。 38 | 39 | #### thread-create/main.c 40 | 41 | ```c 42 | void hare(void *arg) { 43 | int tracklen = *((int *) arg); 44 | while (tracklen) { 45 | tracklen--; 46 | sleep(1); 47 | fprintf(stderr, "Hare ran another step\n"); 48 | } 49 | fprintf(stderr, "Hare done running!\n"); 50 | } 51 | ``` 52 | 53 | `uv_thread_join`不像`pthread_join`那样,允许线程通过第二个参数向父线程返回值。想要传递值,必须使用线程间通信[Inter-thread communication](#inter_thread_communication-pane)。 54 | 55 | ## Synchronization Primitives 56 | 57 | 因为本教程重点不在线程,所以我只罗列了libuv API中一些神奇的地方。剩下的你可以自行阅读pthreads的手册。 58 | 59 | #### Mutexes 60 | 61 | libuv上的互斥量函数与pthread上存在一一映射。如果对pthread上的mutex不是很了解可以看[这里](https://computing.llnl.gov/tutorials/pthreads/)。 62 | 63 | #### libuv mutex functions 64 | 65 | ```c 66 | UV_EXTERN int uv_mutex_init(uv_mutex_t* handle); 67 | UV_EXTERN void uv_mutex_destroy(uv_mutex_t* handle); 68 | UV_EXTERN void uv_mutex_lock(uv_mutex_t* handle); 69 | UV_EXTERN int uv_mutex_trylock(uv_mutex_t* handle); 70 | UV_EXTERN void uv_mutex_unlock(uv_mutex_t* handle); 71 | ``` 72 | 73 | `uv_mutex_init`与`uv_mutex_trylock`在成功执行后,返回0,或者在错误时,返回错误码。 74 | 75 | 如果libuv在编译的时候开启了调试模式,`uv_mutex_destroy()`, `uv_mutex_lock()` 和 `uv_mutex_unlock()`会在出错的地方调用`abort()`中断。类似的,`uv_mutex_trylock()`也同样会在错误发生时中断,而不是返回`EAGAIN`和`EBUSY`。 76 | 77 | 递归地调用互斥量函数在某些系统平台上是支持的,但是你不能太过度依赖。因为例如在BSD上递归地调用互斥量函数会返回错误,比如你准备使用互斥量函数给一个已经上锁的临界区再次上锁的时候,就会出错。比如,像下面这个例子: 78 | 79 | ```c 80 | uv_mutex_lock(a_mutex); 81 | uv_thread_create(thread_id, entry, (void *)a_mutex); 82 | uv_mutex_lock(a_mutex); 83 | // more things here 84 | ``` 85 | 86 | 可以用来等待其他线程初始化一些变量然后释放`a_mutex`锁,但是第二次调用`uv_mutex_lock()`, 在调试模式下会导致程序崩溃,或者是返回错误。 87 | 88 | ##### NOTE 89 | >在linux中是支持递归上锁的,但是在libuv的API中并未实现。 90 | 91 | #### Lock 92 | 93 | 读写锁是更细粒度的实现机制。两个读者线程可以同时从共享区中读取数据。当读者以读模式占有读写锁时,写者不能再占有它。当写者以写模式占有这个锁时,其他的写者或者读者都不能占有它。读写锁在数据库操作中非常常见,下面是一个玩具式的例子: 94 | 95 | #### locks/main.c - simple rwlocks 96 | 97 | ```c 98 | #include 99 | #include 100 | 101 | uv_barrier_t blocker; 102 | uv_rwlock_t numlock; 103 | int shared_num; 104 | 105 | void reader(void *n) 106 | { 107 | int num = *(int *)n; 108 | int i; 109 | for (i = 0; i < 20; i++) { 110 | uv_rwlock_rdlock(&numlock); 111 | printf("Reader %d: acquired lock\n", num); 112 | printf("Reader %d: shared num = %d\n", num, shared_num); 113 | uv_rwlock_rdunlock(&numlock); 114 | printf("Reader %d: released lock\n", num); 115 | } 116 | uv_barrier_wait(&blocker); 117 | } 118 | 119 | void writer(void *n) 120 | { 121 | int num = *(int *)n; 122 | int i; 123 | for (i = 0; i < 20; i++) { 124 | uv_rwlock_wrlock(&numlock); 125 | printf("Writer %d: acquired lock\n", num); 126 | shared_num++; 127 | printf("Writer %d: incremented shared num = %d\n", num, shared_num); 128 | uv_rwlock_wrunlock(&numlock); 129 | printf("Writer %d: released lock\n", num); 130 | } 131 | uv_barrier_wait(&blocker); 132 | } 133 | 134 | int main() 135 | { 136 | uv_barrier_init(&blocker, 4); 137 | 138 | shared_num = 0; 139 | uv_rwlock_init(&numlock); 140 | 141 | uv_thread_t threads[3]; 142 | 143 | int thread_nums[] = {1, 2, 1}; 144 | uv_thread_create(&threads[0], reader, &thread_nums[0]); 145 | uv_thread_create(&threads[1], reader, &thread_nums[1]); 146 | 147 | uv_thread_create(&threads[2], writer, &thread_nums[2]); 148 | 149 | uv_barrier_wait(&blocker); 150 | uv_barrier_destroy(&blocker); 151 | 152 | uv_rwlock_destroy(&numlock); 153 | return 0; 154 | } 155 | ``` 156 | 157 | 试着来执行一下上面的程序,看读者有多少次会同步执行。在有多个写者的时候,调度器会给予他们高优先级。因此,如果你加入两个读者,你会看到所有的读者趋向于在读者得到加锁机会前结束。 158 | 159 | 在上面的例子中,我们也使用了屏障。因此主线程来等待所有的线程都已经结束,最后再将屏障和锁一块回收。 160 | 161 | #### Others 162 | 163 | libuv同样支持[信号量](https://en.wikipedia.org/wiki/Semaphore_programming),[条件变量](https://en.wikipedia.org/wiki/Monitor_synchronization#Waiting_and_signaling)和[屏障](https://en.wikipedia.org/wiki/Barrier_computer_science),而且API的使用方法和pthread中的用法很类似。(如果你对上面的三个名词还不是很熟,可以看[这里](http://www.wuzesheng.com/?p=1668),[这里](http://name5566.com/4535.html),[这里](http://www.cnblogs.com/panhao/p/4653623.html))。 164 | 165 | 还有,libuv提供了一个简单易用的函数`uv_once()`。多个线程调用这个函数,参数可以使用一个uv_once_t和一个指向特定函数的指针,**最终只有一个线程能够执行这个特定函数,并且这个特定函数只会被调用一次**: 166 | 167 | ```c 168 | /* Initialize guard */ 169 | static uv_once_t once_only = UV_ONCE_INIT; 170 | 171 | int i = 0; 172 | 173 | void increment() { 174 | i++; 175 | } 176 | 177 | void thread1() { 178 | /* ... work */ 179 | uv_once(once_only, increment); 180 | } 181 | 182 | void thread2() { 183 | /* ... work */ 184 | uv_once(once_only, increment); 185 | } 186 | 187 | int main() { 188 | /* ... spawn threads */ 189 | } 190 | ``` 191 | 192 | 当所有的线程执行完毕时,`i == 1`。 193 | 194 | 在libuv的v0.11.11版本里,推出了uv_key_t结构和操作[线程局部存储TLS](http://baike.baidu.com/view/598128.htm)的[API](http://docs.libuv.org/en/v1.x/threading.html#thread-local-storage),使用方法同样和pthread类似。 195 | 196 | ##libuv work queue 197 | 198 | `uv_queue_work()`是一个便利的函数,它使得一个应用程序能够在不同的线程运行任务,当任务完成后,回调函数将会被触发。它看起来好像很简单,但是它真正吸引人的地方在于它能够使得任何第三方的库都能以event-loop的方式执行。当使用event-loop的时候,最重要的是不能让loop线程阻塞,或者是执行高cpu占用的程序,因为这样会使得loop慢下来,loop event的高效特性也不能得到很好地发挥。 199 | 200 | 然而,很多带有阻塞的特性的程序(比如最常见的I/O)使用开辟新线程来响应新请求(最经典的‘一个客户,一个线程‘模型)。使用event-loop可以提供另一种实现的方式。libuv提供了一个很好的抽象,使得你能够很好地使用它。 201 | 202 | 下面有一个很好的例子,灵感来自<<[nodejs is cancer](http://teddziuba.github.io/2011/10/node-js-is-cancer.html)>>。我们将要执行fibonacci数列,并且睡眠一段时间,但是将阻塞和cpu占用时间长的任务分配到不同的线程,使得其不会阻塞event loop上的其他任务。 203 | 204 | #### queue-work/main.c - lazy fibonacci 205 | 206 | ```c 207 | void fib(uv_work_t *req) { 208 | int n = *(int *) req->data; 209 | if (random() % 2) 210 | sleep(1); 211 | else 212 | sleep(3); 213 | long fib = fib_(n); 214 | fprintf(stderr, "%dth fibonacci is %lu\n", n, fib); 215 | } 216 | 217 | void after_fib(uv_work_t *req, int status) { 218 | fprintf(stderr, "Done calculating %dth fibonacci\n", *(int *) req->data); 219 | } 220 | ``` 221 | 222 | 任务函数很简单,也还没有运行在线程之上。`uv_work_t`是关键线索,你可以通过`void *data`传递任何数据,使用它来完成线程之间的沟通任务。但是你要确信,当你在多个线程都在运行的时候改变某个东西的时候,能够使用适当的锁。 223 | 224 | 触发器是`uv_queue_work`: 225 | 226 | #### queue-work/main.c 227 | 228 | ```c 229 | int main() { 230 | loop = uv_default_loop(); 231 | 232 | int data[FIB_UNTIL]; 233 | uv_work_t req[FIB_UNTIL]; 234 | int i; 235 | for (i = 0; i < FIB_UNTIL; i++) { 236 | data[i] = i; 237 | req[i].data = (void *) &data[i]; 238 | uv_queue_work(loop, &req[i], fib, after_fib); 239 | } 240 | 241 | return uv_run(loop, UV_RUN_DEFAULT); 242 | } 243 | ``` 244 | 245 | 线程函数fbi()将会在不同的线程中运行,传入`uv_work_t`结构体参数,一旦fib()函数返回,after_fib()会被event loop中的线程调用,然后被传入同样的结构体。 246 | 247 | 为了封装阻塞的库,常见的模式是用[baton](http://nikhilm.github.io/uvbook/utilities.html#baton)来交换数据。 248 | 249 | 从libuv 0.9.4版后,添加了函数`uv_cancel()`。它可以用来取消工作队列中的任务。只有还未开始的任务可以被取消,如果任务已经开始执行或者已经执行完毕,`uv_cancel()`调用会失败。 250 | 251 | 当用户想要终止程序的时候,`uv_cancel()`可以用来清理任务队列中的等待执行的任务。例如,一个音乐播放器可以以歌手的名字对歌曲进行排序,如果这个时候用户想要退出这个程序,`uv_cancel()`就可以做到快速退出,而不用等待执行完任务队列后,再退出。 252 | 253 | 让我们对上述程序做一些修改,用来演示`uv_cancel()`的用法。首先让我们注册一个处理中断的函数。 254 | 255 | #### queue-cancel/main.c 256 | 257 | ```c 258 | int main() { 259 | loop = uv_default_loop(); 260 | 261 | int data[FIB_UNTIL]; 262 | int i; 263 | for (i = 0; i < FIB_UNTIL; i++) { 264 | data[i] = i; 265 | fib_reqs[i].data = (void *) &data[i]; 266 | uv_queue_work(loop, &fib_reqs[i], fib, after_fib); 267 | } 268 | 269 | uv_signal_t sig; 270 | uv_signal_init(loop, &sig); 271 | uv_signal_start(&sig, signal_handler, SIGINT); 272 | 273 | return uv_run(loop, UV_RUN_DEFAULT); 274 | } 275 | ``` 276 | 277 | 当用户通过`Ctrl+C`触发信号时,`uv_cancel()`回收任务队列中所有的任务,如果任务已经开始执行或者执行完毕,`uv_cancel()`返回0。 278 | 279 | #### queue-cancel/main.c 280 | 281 | ```c 282 | void signal_handler(uv_signal_t *req, int signum) 283 | { 284 | printf("Signal received!\n"); 285 | int i; 286 | for (i = 0; i < FIB_UNTIL; i++) { 287 | uv_cancel((uv_req_t*) &fib_reqs[i]); 288 | } 289 | uv_signal_stop(req); 290 | } 291 | ``` 292 | 293 | 对于已经成功取消的任务,他的回调函数的参数`status`会被设置为`UV_ECANCELED`。 294 | 295 | #### queue-cancel/main.c 296 | 297 | ```c 298 | void after_fib(uv_work_t *req, int status) { 299 | if (status == UV_ECANCELED) 300 | fprintf(stderr, "Calculation of %d cancelled.\n", *(int *) req->data); 301 | } 302 | ``` 303 | 304 | `uv_cancel()`函数同样可以用在`uv_fs_t`和`uv_getaddrinfo_t`请求上。对于一系列的文件系统操作函数来说,`uv_fs_t.errorno`会同样被设置为`UV_ECANCELED`。 305 | 306 | ##### Tip 307 | >一个良好设计的程序,应该能够终止一个已经开始运行的长耗时任务。 308 | >Such a worker could periodically check for a variable that only the main process sets to signal termination. 309 | 310 | ##Inter-thread communication 311 | 312 | 很多时候,你希望正在运行的线程之间能够相互发送消息。例如你在运行一个持续时间长的任务(可能使用uv_queue_work),但是你需要在主线程中监视它的进度情况。下面有一个简单的例子,演示了一个下载管理程序向用户展示各个下载线程的进度。 313 | 314 | #### progress/main.c 315 | 316 | ```c 317 | uv_loop_t *loop; 318 | uv_async_t async; 319 | 320 | int main() { 321 | loop = uv_default_loop(); 322 | 323 | uv_work_t req; 324 | int size = 10240; 325 | req.data = (void*) &size; 326 | 327 | uv_async_init(loop, &async, print_progress); 328 | uv_queue_work(loop, &req, fake_download, after); 329 | 330 | return uv_run(loop, UV_RUN_DEFAULT); 331 | } 332 | ``` 333 | 334 | 因为异步的线程通信是基于event-loop的,所以尽管所有的线程都可以是发送方,但是只有在event-loop上的线程可以是接收方(或者说event-loop是接收方)。在上述的代码中,当异步监视者接收到信号的时候,libuv会激发回调函数(print_progress)。 335 | 336 | ##### WARNING 337 | >应该注意: 因为消息的发送是异步的,当`uv_async_send`在另外一个线程中被调用后,回调函数可能会立即被调用, 也可能在稍后的某个时刻被调用。libuv也有可能多次调用`uv_async_send`,但只调用了一次回调函数。唯一可以保证的是: 线程在调用`uv_async_send`之后回调函数可至少被调用一次。 如果你没有未调用的`uv_async_send`, 那么回调函数也不会被调用。 如果你调用了两次(以上)的`uv_async_send`, 而 libuv 暂时还没有机会运行回调函数, 则libuv可能会在多次调用`uv_async_send`后只调用一次回调函数,你的回调函数绝对不会在一次事件中被调用两次(或多次)。 338 | 339 | #### progress/main.c 340 | ```c 341 | void fake_download(uv_work_t *req) { 342 | int size = *((int*) req->data); 343 | int downloaded = 0; 344 | double percentage; 345 | while (downloaded < size) { 346 | percentage = downloaded*100.0/size; 347 | async.data = (void*) &percentage; 348 | uv_async_send(&async); 349 | 350 | sleep(1); 351 | downloaded += (200+random())%1000; // can only download max 1000bytes/sec, 352 | // but at least a 200; 353 | } 354 | } 355 | 356 | ``` 357 | 358 | 在上述的下载函数中,我们修改了进度显示器,使用`uv_async_send`发送进度信息。要记住:`uv_async_send`同样是非阻塞的,调用后会立即返回。 359 | 360 | #### progress/main.c 361 | 362 | ```c 363 | void print_progress(uv_async_t *handle) { 364 | double percentage = *((double*) handle->data); 365 | fprintf(stderr, "Downloaded %.2f%%\n", percentage); 366 | } 367 | ``` 368 | 369 | 函数`print_progress`是标准的libuv模式,从监视器中抽取数据。最后最重要的是把监视器回收。 370 | 371 | #### progress/main.c 372 | ```c 373 | void after(uv_work_t *req, int status) { 374 | fprintf(stderr, "Download complete\n"); 375 | uv_close((uv_handle_t*) &async, NULL); 376 | } 377 | ``` 378 | 379 | 在例子的最后,我们要说下`data`域的滥用,[bnoordhuis](https://github.com/bnoordhuis)指出使用`data`域可能会存在线程安全问题,`uv_async_send()`事实上只是唤醒了event-loop。可以使用互斥量或者读写锁来保证执行顺序的正确性。 380 | 381 | ##### Note 382 | >互斥量和读写锁不能在信号处理函数中正确工作,但是`uv_async_send`可以。 383 | 384 | 一种需要使用`uv_async_send`的场景是,当调用需要线程交互的库时。例如,举一个在node.js中V8引擎的例子,上下文和对象都是与v8引擎的线程绑定的,从另一个线程中直接向v8请求数据会导致返回不确定的结果。但是,考虑到现在很多nodejs的模块都是和第三方库绑定的,可以像下面一样,解决这个问题: 385 | 386 | >1.在node中,第三方库会建立javascript的回调函数,以便回调函数被调用时,能够返回更多的信息。 387 | 388 | ```javascript 389 | var lib = require('lib'); 390 | lib.on_progress(function() { 391 | console.log("Progress"); 392 | }); 393 | 394 | lib.do(); 395 | 396 | // do other stuff 397 | ``` 398 | 399 | >2.`lib.do`应该是非阻塞的,但是第三方库却是阻塞的,所以需要调用`uv_queue_work`函数。 400 | >3.在另外一个线程中完成任务想要调用progress的回调函数,但是不能直接与v8通信,所以需要`uv_async_send`函数。 401 | >4.在主线程(v8线程)中调用的异步回调函数,会在v8的配合下执行javscript的回调函数。(也就是说,主线程会调用回调函数,并且提供v8解析javascript的功能,以便其完成任务)。 402 | -------------------------------------------------------------------------------- /source/utilities.md: -------------------------------------------------------------------------------- 1 | # Utilities 2 | 3 | 本章介绍的工具和技术对于常见的任务非常的实用。libuv吸收了[libev用户手册页](http://pod.tst.eu/http://cvs.schmorp.de/libev/ev.pod#COMMON_OR_USEFUL_IDIOMS_OR_BOTH)中所涵盖的一些模式,并在此基础上对API做了少许的改动。本章还包含了一些无需用完整的一章来介绍的libuv API。 4 | 5 | ## Timers 6 | 7 | 在定时器启动后的特定时间后,定时器会调用回调函数。libuv的定时器还可以设定为,按时间间隔定时启动,而不是只启动一次。 8 | 可以简单地使用超时时间`timeout`作为参数初始化一个定时器,还有一个可选参数`repeat`。定时器能在任何时间被终止。 9 | 10 | ```c 11 | uv_timer_t timer_req; 12 | 13 | uv_timer_init(loop, &timer_req); 14 | uv_timer_start(&timer_req, callback, 5000, 2000); 15 | ``` 16 | 17 | 上述操作会启动一个循环定时器(repeating timer),它会在调用`uv_timer_start`后,5秒(timeout)启动回调函数,然后每隔2秒(repeat)循环启动回调函数。你可以使用: 18 | 19 | ```c 20 | uv_timer_stop(&timer_req); 21 | ``` 22 | 23 | 来停止定时器。这个函数也可以在回调函数中安全地使用。 24 | 25 | 循环的间隔也可以随时定义,使用: 26 | 27 | ```c 28 | uv_timer_set_repeat(uv_timer_t *timer, int64_t repeat); 29 | ``` 30 | 31 | 它会在**可能的时候**发挥作用。如果上述函数是在定时器回调函数中调用的,这意味着: 32 | 33 | >* 如果定时器未设置为循环,这意味着定时器已经停止。需要先用`uv_timer_start`重新启动。 34 | * 如果定时器被设置为循环,那么下一次超时的时间已经被规划好了,所以在切换到新的间隔之前,旧的间隔还会发挥一次作用。 35 | 36 | 函数: 37 | 38 | ```c 39 | int uv_timer_again(uv_timer_t *) 40 | ``` 41 | 42 | **只适用于循环定时器**,相当于停止定时器,然后把原先的`timeout`和`repeat`值都设置为之前的`repeat`值,启动定时器。如果当该函数调用时,定时器未启动,则调用失败(错误码为`UV_EINVAL`)并且返回-1。 43 | 44 | 下面的一节会出现使用定时器的例子。 45 | 46 | ## Event loop reference count 47 | 48 | event-loop在没有了活跃的handle之后,便会终止。整套系统的工作方式是:在handle增加时,event-loop的引用计数加1,在handle停止时,引用计数减少1。当然,libuv也允许手动地更改引用计数,通过使用: 49 | 50 | ```c 51 | void uv_ref(uv_handle_t*); 52 | void uv_unref(uv_handle_t*); 53 | ``` 54 | 55 | 这样,就可以达到允许loop即使在有正在活动的定时器时,仍然能够推出。或者是使用自定义的uv_handle_t对象来使得loop保持工作。 56 | 57 | 第二个函数可以和间隔循环定时器结合使用。你会有一个每隔x秒执行一次的垃圾回收器,或者是你的网络服务器会每隔一段时间向其他人发送一次心跳信号,但是你不想只有在所有垃圾回收完或者出现错误时才能停止他们。如果你想要在你其他的监视器都退出后,终止程序。这时你就可以立即unref定时器,即便定时器这时是loop上唯一还在运行的监视器,你依旧可以停止`uv_run()`。 58 | 59 | 它们同样会出现在node.js中,如js的API中封装的libuv方法。每一个js的对象产生一个`uv_handle_t`(所有监视器的超类),同样可以被uv_ref和uv_unref。 60 | 61 | #### ref-timer/main.c 62 | 63 | ```c 64 | uv_loop_t *loop; 65 | uv_timer_t gc_req; 66 | uv_timer_t fake_job_req; 67 | 68 | int main() { 69 | loop = uv_default_loop(); 70 | 71 | uv_timer_init(loop, &gc_req); 72 | uv_unref((uv_handle_t*) &gc_req); 73 | 74 | uv_timer_start(&gc_req, gc, 0, 2000); 75 | 76 | // could actually be a TCP download or something 77 | uv_timer_init(loop, &fake_job_req); 78 | uv_timer_start(&fake_job_req, fake_job, 9000, 0); 79 | return uv_run(loop, UV_RUN_DEFAULT); 80 | } 81 | ``` 82 | 83 | 首先初始化垃圾回收器的定时器,然后在立刻`unref`它。注意观察9秒之后,此时fake_job完成,程序会自动退出,即使垃圾回收器还在运行。 84 | 85 | ## Idler pattern 86 | 87 | 空转的回调函数会在每一次的event-loop循环激发一次。空转的回调函数可以用来执行一些优先级较低的活动。比如,你可以向开发者发送应用程序的每日性能表现情况,以便于分析,或者是使用用户应用cpu时间来做[SETI](http://www.seti.org)运算:)。空转程序还可以用于GUI应用。比如你在使用event-loop来下载文件,如果tcp连接未中断而且当前并没有其他的事件,则你的event-loop会阻塞,这也就意味着你的下载进度条会停滞,用户会面对一个无响应的程序。面对这种情况,空转监视器可以保持UI可操作。 88 | 89 | #### idle-compute/main.c 90 | 91 | ```c 92 | uv_loop_t *loop; 93 | uv_fs_t stdin_watcher; 94 | uv_idle_t idler; 95 | char buffer[1024]; 96 | 97 | int main() { 98 | loop = uv_default_loop(); 99 | 100 | uv_idle_init(loop, &idler); 101 | 102 | uv_buf_t buf = uv_buf_init(buffer, 1024); 103 | uv_fs_read(loop, &stdin_watcher, 0, &buf, 1, -1, on_type); 104 | uv_idle_start(&idler, crunch_away); 105 | return uv_run(loop, UV_RUN_DEFAULT); 106 | } 107 | ``` 108 | 109 | 上述程序中,我们将空转监视器和我们真正关心的事件排在一起。`crunch_away`会被循环地调用,直到输入字符并回车。然后程序会被中断很短的时间,用来处理数据读取,然后在接着调用空转的回调函数。 110 | 111 | #### idle-compute/main.c 112 | 113 | ```c 114 | void crunch_away(uv_idle_t* handle) { 115 | // Compute extra-terrestrial life 116 | // fold proteins 117 | // computer another digit of PI 118 | // or similar 119 | fprintf(stderr, "Computing PI...\n"); 120 | // just to avoid overwhelming your terminal emulator 121 | uv_idle_stop(handle); 122 | } 123 | ``` 124 | 125 | ## Passing data to worker thread 126 | 127 | 在使用`uv_queue_work`的时候,你通常需要给工作线程传递复杂的数据。解决方案是自定义struct,然后使用`uv_work_t.data`指向它。一个稍微的不同是必须让`uv_work_t`作为这个自定义struct的成员之一(把这叫做接力棒)。这么做就可以使得,同时回收数据和`uv_wortk_t`。 128 | 129 | ```c 130 | struct ftp_baton { 131 | uv_work_t req; 132 | char *host; 133 | int port; 134 | char *username; 135 | char *password; 136 | } 137 | ``` 138 | 139 | ```c 140 | ftp_baton *baton = (ftp_baton*) malloc(sizeof(ftp_baton)); 141 | baton->req.data = (void*) baton; 142 | baton->host = strdup("my.webhost.com"); 143 | baton->port = 21; 144 | // ... 145 | 146 | uv_queue_work(loop, &baton->req, ftp_session, ftp_cleanup); 147 | ``` 148 | 149 | 现在我们创建完了接力棒,并把它排入了队列中。 150 | 151 | 现在就可以随性所欲地获取自己想要的数据啦。 152 | 153 | ```c 154 | void ftp_session(uv_work_t *req) { 155 | ftp_baton *baton = (ftp_baton*) req->data; 156 | 157 | fprintf(stderr, "Connecting to %s\n", baton->host); 158 | } 159 | 160 | void ftp_cleanup(uv_work_t *req) { 161 | ftp_baton *baton = (ftp_baton*) req->data; 162 | 163 | free(baton->host); 164 | // ... 165 | free(baton); 166 | } 167 | ``` 168 | 169 | 我们既回收了接力棒,同时也回收了监视器。 170 | 171 | ## External I/O with polling 172 | 173 | 通常在使用第三方库的时候,需要应对他们自己的IO,还有保持监视他们的socket和内部文件。在此情形下,不可能使用标准的IO流操作,但第三方库仍然能整合进event-loop中。所有这些需要的就是,第三方库就必须允许你访问它的底层文件描述符,并且提供可以处理有用户定义的细微任务的函数。但是一些第三库并不允许你这么做,他们只提供了一个标准的阻塞IO函数,此函数会完成所有的工作并返回。在event-loop的线程直接使用它们是不明智的,而是应该使用libuv的工作线程。当然,这也意味着失去了对第三方库的颗粒化控制。 174 | 175 | libuv的`uv_poll`简单地监视了使用了操作系统的监控机制的文件描述符。从某方面说,libuv实现的所有的IO操作,的背后均有`uv_poll`的支持。无论操作系统何时监视到文件描述符的改变,libuv都会调用响应的回调函数。 176 | 177 | 现在我们简单地实现一个下载管理程序,它会通过[libcurl](http://curl.haxx.se/libcurl/)来下载文件。我们不会直接控制libcurl,而是使用libuv的event-loop,通过非阻塞的异步的[多重接口](http://curl.haxx.se/libcurl/c/libcurl-multi.html)来处理下载,与此同时,libuv会监控IO的就绪状态。 178 | 179 | #### uvwget/main.c - The setup 180 | 181 | ```c 182 | #include 183 | #include 184 | #include 185 | #include 186 | #include 187 | 188 | uv_loop_t *loop; 189 | CURLM *curl_handle; 190 | uv_timer_t timeout; 191 | } 192 | 193 | int main(int argc, char **argv) { 194 | loop = uv_default_loop(); 195 | 196 | if (argc <= 1) 197 | return 0; 198 | 199 | if (curl_global_init(CURL_GLOBAL_ALL)) { 200 | fprintf(stderr, "Could not init cURL\n"); 201 | return 1; 202 | } 203 | 204 | uv_timer_init(loop, &timeout); 205 | 206 | curl_handle = curl_multi_init(); 207 | curl_multi_setopt(curl_handle, CURLMOPT_SOCKETFUNCTION, handle_socket); 208 | curl_multi_setopt(curl_handle, CURLMOPT_TIMERFUNCTION, start_timeout); 209 | 210 | while (argc-- > 1) { 211 | add_download(argv[argc], argc); 212 | } 213 | 214 | uv_run(loop, UV_RUN_DEFAULT); 215 | curl_multi_cleanup(curl_handle); 216 | return 0; 217 | } 218 | ``` 219 | 220 | 每种库整合进libuv的方式都是不同的。以libcurl的例子来说,我们注册了两个回调函数。socket回调函数`handle_socket`会在socket状态改变的时候被触发,因此我们不得不开始轮询它。`start_timeout`是libcurl用来告知我们下一次的超时间隔的,之后我们就应该不管当前IO状态,驱动libcurl向前。这些也就是libcurl能处理错误或驱动下载进度向前的原因。 221 | 222 | 可以这么调用下载器: 223 | 224 | ``` 225 | $ ./uvwget [url1] [url2] ... 226 | ``` 227 | 228 | 我们可以把url当成参数传入程序。 229 | 230 | #### uvwget/main.c - Adding urls 231 | 232 | ```c 233 | void add_download(const char *url, int num) { 234 | char filename[50]; 235 | sprintf(filename, "%d.download", num); 236 | FILE *file; 237 | 238 | file = fopen(filename, "w"); 239 | if (file == NULL) { 240 | fprintf(stderr, "Error opening %s\n", filename); 241 | return; 242 | } 243 | 244 | CURL *handle = curl_easy_init(); 245 | curl_easy_setopt(handle, CURLOPT_WRITEDATA, file); 246 | curl_easy_setopt(handle, CURLOPT_URL, url); 247 | curl_multi_add_handle(curl_handle, handle); 248 | fprintf(stderr, "Added download %s -> %s\n", url, filename); 249 | } 250 | ``` 251 | 252 | 我们允许libcurl直接向文件写入数据。 253 | 254 | `start_timeout`会被libcurl立即调用。它会启动一个libuv的定时器,使用`CURL_SOCKET_TIMEOUT`驱动`curl_multi_socket_action`,当其超时时,调用它。`curl_multi_socket_action`会驱动libcurl,也会在socket状态改变的时候被调用。但在我们深入讲解它之前,我们需要轮询监听socket,等待`handle_socket`被调用。 255 | 256 | #### uvwget/main.c - Setting up polling 257 | 258 | ```c 259 | void start_timeout(CURLM *multi, long timeout_ms, void *userp) { 260 | if (timeout_ms <= 0) 261 | timeout_ms = 1; /* 0 means directly call socket_action, but we'll do it in a bit */ 262 | uv_timer_start(&timeout, on_timeout, timeout_ms, 0); 263 | } 264 | 265 | int handle_socket(CURL *easy, curl_socket_t s, int action, void *userp, void *socketp) { 266 | curl_context_t *curl_context; 267 | if (action == CURL_POLL_IN || action == CURL_POLL_OUT) { 268 | if (socketp) { 269 | curl_context = (curl_context_t*) socketp; 270 | } 271 | else { 272 | curl_context = create_curl_context(s); 273 | curl_multi_assign(curl_handle, s, (void *) curl_context); 274 | } 275 | } 276 | 277 | switch (action) { 278 | case CURL_POLL_IN: 279 | uv_poll_start(&curl_context->poll_handle, UV_READABLE, curl_perform); 280 | break; 281 | case CURL_POLL_OUT: 282 | uv_poll_start(&curl_context->poll_handle, UV_WRITABLE, curl_perform); 283 | break; 284 | case CURL_POLL_REMOVE: 285 | if (socketp) { 286 | uv_poll_stop(&((curl_context_t*)socketp)->poll_handle); 287 | destroy_curl_context((curl_context_t*) socketp); 288 | curl_multi_assign(curl_handle, s, NULL); 289 | } 290 | break; 291 | default: 292 | abort(); 293 | } 294 | 295 | return 0; 296 | } 297 | ``` 298 | 299 | 我们关心的是socket的文件描述符s,还有action。对应每一个socket,我们都创造了`uv_poll_t`,并用`curl_multi_assign`把它们关联起来。每当回调函数被调用时,`socketp`都会指向它。 300 | 301 | 在下载完成或失败后,libcurl需要移除poll。所以我们停止并回收了poll的handle。 302 | 303 | 我们使用`UV_READABLE`或`UV_WRITABLE`开始轮询,基于libcurl想要监视的事件。当socket已经准备好读或写后,libuv会调用轮询的回调函数。在相同的handle上调用多次`uv_poll_start`是被允许的,这么做可以更新事件的参数。`curl_perform`是整个程序的关键。 304 | 305 | #### uvwget/main.c - Driving libcurl. 306 | 307 | ```c 308 | void curl_perform(uv_poll_t *req, int status, int events) { 309 | uv_timer_stop(&timeout); 310 | int running_handles; 311 | int flags = 0; 312 | if (status < 0) flags = CURL_CSELECT_ERR; 313 | if (!status && events & UV_READABLE) flags |= CURL_CSELECT_IN; 314 | if (!status && events & UV_WRITABLE) flags |= CURL_CSELECT_OUT; 315 | 316 | curl_context_t *context; 317 | 318 | context = (curl_context_t*)req; 319 | 320 | curl_multi_socket_action(curl_handle, context->sockfd, flags, &running_handles); 321 | check_multi_info(); 322 | } 323 | ``` 324 | 325 | 首先我们要做的是停止定时器,因为内部还有其他要做的事。接下来我们我们依据触发回调函数的事件,来设置flag。然后,我们使用上述socket和flag作为参数,来调用`curl_multi_socket_action`。在此刻libcurl会在内部完成所有的工作,然后尽快地返回事件驱动程序在主线程中急需的数据。libcurl会在自己的队列中将传输进度的消息排队。对于我们来说,我们只关心是否传输完成,这类消息。所以我们将这类消息提取出来,并将传输完成的handle回收。 326 | 327 | #### uvwget/main.c - Reading transfer status. 328 | 329 | ```c 330 | void check_multi_info(void) { 331 | char *done_url; 332 | CURLMsg *message; 333 | int pending; 334 | 335 | while ((message = curl_multi_info_read(curl_handle, &pending))) { 336 | switch (message->msg) { 337 | case CURLMSG_DONE: 338 | curl_easy_getinfo(message->easy_handle, CURLINFO_EFFECTIVE_URL, 339 | &done_url); 340 | printf("%s DONE\n", done_url); 341 | 342 | curl_multi_remove_handle(curl_handle, message->easy_handle); 343 | curl_easy_cleanup(message->easy_handle); 344 | break; 345 | 346 | default: 347 | fprintf(stderr, "CURLMSG default\n"); 348 | abort(); 349 | } 350 | } 351 | } 352 | ``` 353 | 354 | ## Loading libraries 355 | 356 | libuv提供了一个跨平台的API来加载[共享库shared libraries](http://liaoph.com/linux-shared-libary/)。这就可以用来实现你自己的插件/扩展/模块系统,它们可以被nodejs通过`require()`调用。只要你的库输出的是正确的符号,用起来还是很简单的。在载入第三方库的时候,要注意错误和安全检查,否则你的程序就会表现出不可预测的行为。下面这个例子实现了一个简单的插件,它只是打印出了自己的名字。 357 | 358 | 首先看下提供给插件作者的接口。 359 | 360 | #### plugin/plugin.h 361 | 362 | ```c 363 | #ifndef UVBOOK_PLUGIN_SYSTEM 364 | #define UVBOOK_PLUGIN_SYSTEM 365 | 366 | // Plugin authors should use this to register their plugins with mfp. 367 | void mfp_register(const char *name); 368 | 369 | #endif 370 | ``` 371 | 372 | 你可以在你的程序中给插件添加更多有用的功能(mfp is My Fancy Plugin)。使用了这个api的插件的例子: 373 | 374 | #### plugin/hello.c 375 | 376 | ```c 377 | #include "plugin.h" 378 | 379 | void initialize() { 380 | mfp_register("Hello World!"); 381 | } 382 | ``` 383 | 384 | 我们的接口定义了,所有的插件都应该有一个能被程序调用的`initialize`函数。这个插件被编译成了共享库,因此可以被我们的程序在运行的时候载入。 385 | 386 | ``` 387 | $ ./plugin libhello.dylib 388 | Loading libhello.dylib 389 | Registered plugin "Hello World!" 390 | ``` 391 | 392 | ##### Note 393 | >共享库的后缀名在不同平台上是不一样的。在Linux上是libhello.so。 394 | 395 | 使用`uv_dlopen`首先载入了共享库`libhello.dylib`。再使用`uv_dlsym`获取了该插件的`initialize`函数,最后在调用它。 396 | 397 | #### plugin/main.c 398 | 399 | ```c 400 | #include "plugin.h" 401 | 402 | typedef void (*init_plugin_function)(); 403 | 404 | void mfp_register(const char *name) { 405 | fprintf(stderr, "Registered plugin \"%s\"\n", name); 406 | } 407 | 408 | int main(int argc, char **argv) { 409 | if (argc == 1) { 410 | fprintf(stderr, "Usage: %s [plugin1] [plugin2] ...\n", argv[0]); 411 | return 0; 412 | } 413 | 414 | uv_lib_t *lib = (uv_lib_t*) malloc(sizeof(uv_lib_t)); 415 | while (--argc) { 416 | fprintf(stderr, "Loading %s\n", argv[argc]); 417 | if (uv_dlopen(argv[argc], lib)) { 418 | fprintf(stderr, "Error: %s\n", uv_dlerror(lib)); 419 | continue; 420 | } 421 | 422 | init_plugin_function init_plugin; 423 | if (uv_dlsym(lib, "initialize", (void **) &init_plugin)) { 424 | fprintf(stderr, "dlsym error: %s\n", uv_dlerror(lib)); 425 | continue; 426 | } 427 | 428 | init_plugin(); 429 | } 430 | 431 | return 0; 432 | } 433 | ``` 434 | 435 | 函数`uv_dlopen`需要传入一个共享库的路径作为参数。当它成功时返回0,出错时返回-1。使用`uv_dlerror`可以获取出错的消息。 436 | 437 | `uv_dlsym`的第三个参数保存了一个指向第二个参数所保存的函数的指针。`init_plugin_function`是一个函数的指针,它指向了我们所需要的程序插件的函数。 438 | 439 | ## TTY 440 | 441 | 文字终端长期支持非常标准化的[控制序列](https://en.wikipedia.org/wiki/ANSI_escape_code)。它经常被用来增强终端输出的可读性。例如`grep --colour`。libuv提供了跨平台的,`uv_tty_t`抽象(stream)和相关的处理ANSI escape codes 的函数。这也就是说,libuv同样在Windows上实现了对等的ANSI codes,并且提供了获取终端信息的函数。 442 | 443 | 首先要做的是,使用读/写文件描述符来初始化`uv_tty_t`。如下: 444 | 445 | ```c 446 | int uv_tty_init(uv_loop_t*, uv_tty_t*, uv_file fd, int readable) 447 | ``` 448 | 449 | 设置`readable`为true,意味着你打算使用`uv_read_start`从stream从中读取数据。 450 | 451 | 最好还要使用`uv_tty_set_mode`来设置其为正常模式。也就是运行大多数的TTY格式,流控制和其他的设置。其他的模式还有[这些](http://docs.libuv.org/en/v1.x/tty.html#c.uv_tty_mode_t)。 452 | 453 | 记得当你的程序退出后,要使用`uv_tty_reset_mode`恢复终端的状态。这才是礼貌的做法。另外要注意礼貌的地方是关心重定向。如果使用者将你的命令的输出重定向到文件,控制序列不应该被重写,因为这会阻碍可读性和grep。为了保证文件描述符确实是TTY,可以使用`uv_guess_handle`函数,比较返回值是否为`UV_TTY`。 454 | 455 | 下面是一个把白字打印到红色背景上的例子。 456 | 457 | #### tty/main.c 458 | 459 | ```c 460 | #include 461 | #include 462 | #include 463 | #include 464 | 465 | uv_loop_t *loop; 466 | uv_tty_t tty; 467 | int main() { 468 | loop = uv_default_loop(); 469 | 470 | uv_tty_init(loop, &tty, 1, 0); 471 | uv_tty_set_mode(&tty, UV_TTY_MODE_NORMAL); 472 | 473 | if (uv_guess_handle(1) == UV_TTY) { 474 | uv_write_t req; 475 | uv_buf_t buf; 476 | buf.base = "\033[41;37m"; 477 | buf.len = strlen(buf.base); 478 | uv_write(&req, (uv_stream_t*) &tty, &buf, 1, NULL); 479 | } 480 | 481 | uv_write_t req; 482 | uv_buf_t buf; 483 | buf.base = "Hello TTY\n"; 484 | buf.len = strlen(buf.base); 485 | uv_write(&req, (uv_stream_t*) &tty, &buf, 1, NULL); 486 | uv_tty_reset_mode(); 487 | return uv_run(loop, UV_RUN_DEFAULT); 488 | } 489 | ``` 490 | 491 | 最后要说的是`uv_tty_get_winsize()`,它能获取到终端的宽和长,当成功获取后返回0。下面这个小程序实现了一个动画的效果。 492 | 493 | #### tty-gravity/main.c 494 | 495 | ```c 496 | #include 497 | #include 498 | #include 499 | #include 500 | 501 | uv_loop_t *loop; 502 | uv_tty_t tty; 503 | uv_timer_t tick; 504 | uv_write_t write_req; 505 | int width, height; 506 | int pos = 0; 507 | char *message = " Hello TTY "; 508 | 509 | void update(uv_timer_t *req) { 510 | char data[500]; 511 | 512 | uv_buf_t buf; 513 | buf.base = data; 514 | buf.len = sprintf(data, "\033[2J\033[H\033[%dB\033[%luC\033[42;37m%s", 515 | pos, 516 | (unsigned long) (width-strlen(message))/2, 517 | message); 518 | uv_write(&write_req, (uv_stream_t*) &tty, &buf, 1, NULL); 519 | 520 | pos++; 521 | if (pos > height) { 522 | uv_tty_reset_mode(); 523 | uv_timer_stop(&tick); 524 | } 525 | } 526 | 527 | int main() { 528 | loop = uv_default_loop(); 529 | 530 | uv_tty_init(loop, &tty, 1, 0); 531 | uv_tty_set_mode(&tty, 0); 532 | 533 | if (uv_tty_get_winsize(&tty, &width, &height)) { 534 | fprintf(stderr, "Could not get TTY information\n"); 535 | uv_tty_reset_mode(); 536 | return 1; 537 | } 538 | 539 | fprintf(stderr, "Width %d, height %d\n", width, height); 540 | uv_timer_init(loop, &tick); 541 | uv_timer_start(&tick, update, 200, 200); 542 | return uv_run(loop, UV_RUN_DEFAULT); 543 | } 544 | ``` 545 | 546 | escape codes的对应表如下: 547 | 548 | 代码 | 意义 549 | ------------ | ------------- 550 | 2 J | Clear part of the screen, 2 is entire screen 551 | H | Moves cursor to certain position, default top-left 552 | n B | Moves cursor down by n lines 553 | n C | Moves cursor right by n columns 554 | m | Obeys string of display settings, in this case green background (40+2), white text (30+7) 555 | 556 | 正如你所见,它能输出酷炫的效果,你甚至可以发挥想象,用它来制作电子游戏。更有趣的输出,可以使用`http://www.gnu.org/software/ncurses/ncurses.html`。 557 | 558 | 559 | --------------------------------------------------------------------------------