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