pipe_test.c 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. /*
  2. * hio_create_pipe test
  3. *
  4. * @build make examples
  5. * @test bin/pipe_test
  6. *
  7. */
  8. #include "hloop.h"
  9. #include "htime.h"
  10. static hio_t* pipeio[2] = { NULL, NULL };
  11. static void on_read(hio_t* io, void* buf, int readbytes) {
  12. printf("< %.*s\n", readbytes, (char*)buf);
  13. }
  14. static void on_timer_write(htimer_t* timer) {
  15. char str[DATETIME_FMT_BUFLEN] = {0};
  16. datetime_t dt = datetime_now();
  17. datetime_fmt(&dt, str);
  18. hio_write(pipeio[1], str, strlen(str));
  19. }
  20. static void on_timer_stop(htimer_t* timer) {
  21. hio_close(pipeio[0]);
  22. hio_close(pipeio[1]);
  23. hloop_stop(hevent_loop(timer));
  24. }
  25. int main(int argc, char** argv) {
  26. hloop_t* loop = hloop_new(0);
  27. int ret = hio_create_pipe(loop, pipeio);
  28. if (ret != 0) {
  29. printf("hio_create_pipe failed!\n");
  30. return -10;
  31. }
  32. printf("pipefd %d<=>%d\n", hio_fd(pipeio[0]), hio_fd(pipeio[1]));
  33. hio_setcb_read(pipeio[0], on_read);
  34. hio_read(pipeio[0]);
  35. htimer_add(loop, on_timer_write, 1000, INFINITE);
  36. htimer_add(loop, on_timer_stop, 10000, 1);
  37. hloop_run(loop);
  38. hloop_free(&loop);
  39. return 0;
  40. }