Home | History | Annotate | Line # | Download | only in uvcat
main.c revision 1.1
      1 #include <assert.h>
      2 #include <stdio.h>
      3 #include <fcntl.h>
      4 #include <unistd.h>
      5 #include <uv.h>
      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