1#include <stdio.h> 2 3#include <uv.h> 4 5uv_loop_t *loop; 6uv_fs_t stdin_watcher; 7uv_idle_t idler; 8char buffer[1024]; 9 10void 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 20void 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 34int 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