Skip to content

Instantly share code, notes, and snippets.

@mmaxs
Created May 30, 2016 10:07
Show Gist options
  • Save mmaxs/eebd47945238fb647dbd8681d153f9cf to your computer and use it in GitHub Desktop.
Save mmaxs/eebd47945238fb647dbd8681d153f9cf to your computer and use it in GitHub Desktop.
#include <uv.h>
#include <stdlib.h>
#include <stdio.h>
#define PRINT_UV_ERR(prefix, code) do {\
fflush(stdout);\
fprintf(stderr, "%s: %s (%i): %s\n", prefix, uv_err_name(code), (int)(code), uv_strerror(code));\
fflush(stderr);\
} while (0)
/* assume that stdin and stdout can be handled with as files */
uv_file in, out;
const size_t IO_BUF_SIZE = 65536;
void fs_read_cb(uv_fs_t*);
void fs_write_cb(uv_fs_t*);
int main(int _argc, char *_argv[])
{
uv_loop_t *loop = uv_default_loop();
in = fileno(stdin);
out = fileno(stdout);
/* initialize a buffer descriptor with a newly allocated I/O buffer */
uv_buf_t buf = uv_buf_init((char*)malloc(IO_BUF_SIZE), IO_BUF_SIZE);
/* create a read request descriptor */
uv_fs_t *rd = (uv_fs_t*)malloc(sizeof(uv_fs_t));
/* save the reference to the input buffer along with the read request */
rd->data = buf.base;
/* fire up the read request */
uv_fs_read(loop, rd, in, &buf, 1, -1, fs_read_cb);
return uv_run(loop, UV_RUN_DEFAULT);
}
void fs_read_cb(uv_fs_t *_req)
{
/* check for EOF status */
ssize_t nread = _req->result == 0 ? UV_EOF : _req->result;
if (nread < 0)
{
PRINT_UV_ERR("read", nread);
/* free up the memory allocated for the I/O buffer */
free(_req->data);
uv_fs_req_cleanup(_req);
free(_req);
return;
};
/* schedule a write request */
{
/* initialize a new buffer descriptor specifying the actual data length */
uv_buf_t buf = uv_buf_init(_req->data, nread);
/* create a write request descriptor */
uv_fs_t *wr = (uv_fs_t*)malloc(sizeof(uv_fs_t));
/* save the reference to the output buffer along with the write request */
wr->data = buf.base;
/* fire up the write request */
uv_fs_write(_req->loop, wr, out, &buf, 1, -1, fs_write_cb);
}
/* schedule the next read iteration */
{
uv_loop_t *loop = _req->loop;
/* read request has completed, we can reuse its descriptor after cleanup */
uv_fs_req_cleanup(_req);
/* initialize a new buffer descriptor with a newly allocated I/O buffer */
uv_buf_t buf = uv_buf_init((char*)malloc(IO_BUF_SIZE), IO_BUF_SIZE);
/* save the reference to the input buffer along with the read request */
_req->data = buf.base;
/* fire up the read request */
uv_fs_read(loop, _req, in, &buf, 1, -1, fs_read_cb);
}
}
void fs_write_cb(uv_fs_t *_req)
{
if (_req->result < 0) PRINT_UV_ERR("write", _req->result);
/* free up the memory allocated for the I/O buffer */
free(_req->data);
uv_fs_req_cleanup(_req);
free(_req);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment