#include <fcntl.h>
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdbool.h>
#include <stdlib.h>
#include <sys/select.h>
#include <poll.h>

#define FIFO_NAME "example_fifo"

int main() {
  unsigned int timeout_seconds = 2;

  while (true) {
    int fd = open(FIFO_NAME, O_RDONLY | O_NONBLOCK);
    if (fd < 0) {
      perror("open");
      return EXIT_FAILURE;
    }

    struct pollfd waiter = {.fd = fd, .events = POLLIN};

    while (true) {
      bool stop = false;

      int poll_result = poll(&waiter, 1, timeout_seconds * 1000);
      switch (poll_result) {
      case 0:
        puts("No data from fifo");
        break;

      case 1:
        if (waiter.revents & POLLIN) {
          char buffer[BUFSIZ];
          ssize_t len = read(fd, buffer, sizeof(buffer));
          if (len < 0) {
            perror("read");
            return EXIT_FAILURE;
          }

          printf("Data: %s\n", buffer);
        } else if (waiter.revents & POLLERR) {
          puts("Got a POLLERR");
          return EXIT_FAILURE;
        } else if (waiter.revents & POLLHUP) {
          stop=true; // Writer closed its end
          break;
        }
        break;

      default:
        perror("poll error");
        return EXIT_FAILURE;
      }

      if (stop) {break;}
    }

    if (close(fd) < 0) {
      perror("close");
      return EXIT_FAILURE;
    }
  }

  return EXIT_SUCCESS;
}
