main.c 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. #include <stdio.h>
  2. #include <fcntl.h>
  3. #include <unistd.h>
  4. #include <string.h>
  5. #include <stdlib.h>
  6. #include <uv.h>
  7. typedef struct {
  8. uv_write_t req;
  9. uv_buf_t buf;
  10. } write_req_t;
  11. uv_loop_t *loop;
  12. uv_pipe_t stdin_pipe;
  13. uv_pipe_t stdout_pipe;
  14. uv_pipe_t file_pipe;
  15. void alloc_buffer(uv_handle_t *handle, size_t suggested_size, uv_buf_t *buf) {
  16. *buf = uv_buf_init((char*) malloc(suggested_size), suggested_size);
  17. }
  18. void free_write_req(uv_write_t *req) {
  19. write_req_t *wr = (write_req_t*) req;
  20. free(wr->buf.base);
  21. free(wr);
  22. }
  23. void on_stdout_write(uv_write_t *req, int status) {
  24. free_write_req(req);
  25. }
  26. void on_file_write(uv_write_t *req, int status) {
  27. free_write_req(req);
  28. }
  29. void write_data(uv_stream_t *dest, size_t size, uv_buf_t buf, uv_write_cb cb) {
  30. write_req_t *req = (write_req_t*) malloc(sizeof(write_req_t));
  31. req->buf = uv_buf_init((char*) malloc(size), size);
  32. memcpy(req->buf.base, buf.base, size);
  33. uv_write((uv_write_t*) req, (uv_stream_t*)dest, &req->buf, 1, cb);
  34. }
  35. void read_stdin(uv_stream_t *stream, ssize_t nread, const uv_buf_t *buf) {
  36. if (nread < 0){
  37. if (nread == UV_EOF){
  38. // end of file
  39. uv_close((uv_handle_t *)&stdin_pipe, NULL);
  40. uv_close((uv_handle_t *)&stdout_pipe, NULL);
  41. uv_close((uv_handle_t *)&file_pipe, NULL);
  42. }
  43. } else if (nread > 0) {
  44. write_data((uv_stream_t *)&stdout_pipe, nread, *buf, on_stdout_write);
  45. write_data((uv_stream_t *)&file_pipe, nread, *buf, on_file_write);
  46. }
  47. // OK to free buffer as write_data copies it.
  48. if (buf->base)
  49. free(buf->base);
  50. }
  51. int main(int argc, char **argv) {
  52. loop = uv_default_loop();
  53. uv_pipe_init(loop, &stdin_pipe, 0);
  54. uv_pipe_open(&stdin_pipe, 0);
  55. uv_pipe_init(loop, &stdout_pipe, 0);
  56. uv_pipe_open(&stdout_pipe, 1);
  57. uv_fs_t file_req;
  58. int fd = uv_fs_open(loop, &file_req, argv[1], O_CREAT | O_RDWR, 0644, NULL);
  59. uv_pipe_init(loop, &file_pipe, 0);
  60. uv_pipe_open(&file_pipe, fd);
  61. uv_read_start((uv_stream_t*)&stdin_pipe, alloc_buffer, read_stdin);
  62. uv_run(loop, UV_RUN_DEFAULT);
  63. return 0;
  64. }