1 1.1 christos #include <assert.h> 2 1.1 christos #include <stdio.h> 3 1.1 christos #include <fcntl.h> 4 1.1 christos #include <uv.h> 5 1.1 christos 6 1.1 christos void on_read(uv_fs_t *req); 7 1.1 christos 8 1.1 christos uv_fs_t open_req; 9 1.1 christos uv_fs_t read_req; 10 1.1 christos uv_fs_t write_req; 11 1.1 christos 12 1.1 christos static char buffer[1024]; 13 1.1 christos 14 1.1 christos static uv_buf_t iov; 15 1.1 christos 16 1.1 christos void on_write(uv_fs_t *req) { 17 1.1 christos if (req->result < 0) { 18 1.1 christos fprintf(stderr, "Write error: %s\n", uv_strerror((int)req->result)); 19 1.1 christos } 20 1.1 christos else { 21 1.1 christos uv_fs_read(uv_default_loop(), &read_req, open_req.result, &iov, 1, -1, on_read); 22 1.1 christos } 23 1.1 christos } 24 1.1 christos 25 1.1 christos void on_read(uv_fs_t *req) { 26 1.1 christos if (req->result < 0) { 27 1.1 christos fprintf(stderr, "Read error: %s\n", uv_strerror(req->result)); 28 1.1 christos } 29 1.1 christos else if (req->result == 0) { 30 1.1 christos uv_fs_t close_req; 31 1.1 christos // synchronous 32 1.1 christos uv_fs_close(uv_default_loop(), &close_req, open_req.result, NULL); 33 1.1 christos } 34 1.1 christos else if (req->result > 0) { 35 1.1 christos iov.len = req->result; 36 1.1 christos uv_fs_write(uv_default_loop(), &write_req, 1, &iov, 1, -1, on_write); 37 1.1 christos } 38 1.1 christos } 39 1.1 christos 40 1.1 christos void on_open(uv_fs_t *req) { 41 1.1 christos // The request passed to the callback is the same as the one the call setup 42 1.1 christos // function was passed. 43 1.1 christos assert(req == &open_req); 44 1.1 christos if (req->result >= 0) { 45 1.1 christos iov = uv_buf_init(buffer, sizeof(buffer)); 46 1.1 christos uv_fs_read(uv_default_loop(), &read_req, req->result, 47 1.1 christos &iov, 1, -1, on_read); 48 1.1 christos } 49 1.1 christos else { 50 1.1 christos fprintf(stderr, "error opening file: %s\n", uv_strerror((int)req->result)); 51 1.1 christos } 52 1.1 christos } 53 1.1 christos 54 1.1 christos int main(int argc, char **argv) { 55 1.1 christos uv_fs_open(uv_default_loop(), &open_req, argv[1], O_RDONLY, 0, on_open); 56 1.1 christos uv_run(uv_default_loop(), UV_RUN_DEFAULT); 57 1.1 christos 58 1.1 christos uv_fs_req_cleanup(&open_req); 59 1.1 christos uv_fs_req_cleanup(&read_req); 60 1.1 christos uv_fs_req_cleanup(&write_req); 61 1.1 christos return 0; 62 1.1 christos } 63