#include <stdio.h>
#include <fcntl.h>
#include <poll.h>

#define FIFONAME "/tmp/myfifo"

static const char *
decode_events(int events)
{
	char *ncresult;
	const char *result;

	switch (events) {
		case POLLIN:
			result = "POLLIN";
			break;
		case POLLHUP:
			result = "POLLHUP";
			break;
		case POLLIN | POLLHUP:
			result = "POLLIN | POLLHUP";
			break;
		case POLLOUT:
			result = "POLLOUT";
			break;
		case POLLOUT | POLLERR:
			result = "POLLOUT | POLLERR";
			break;
		case POLLERR:
			result = "POLLERR";
			break;
		case POLLNVAL:
			result = "POLLNVAL";
			break;
		default:
			asprintf(&ncresult, "%#x", events);
			result = ncresult;
			break;
	}
	return (result);
}

int
main()
{
	struct pollfd pfd;
	int fdr, fdw, res;
	char buf[256];

	if (mkfifo(FIFONAME, 0700) < 0)
		err(-1, "makefifo: mkfifo: %s", FIFONAME);

	fdr = open(FIFONAME, O_RDONLY | O_NONBLOCK);
	if (fdr < 0)
		err(1, "open for read");

	fdw = open(FIFONAME, O_WRONLY | O_NONBLOCK);
	if (fdr < 0)
		err(1, "open for write");

	pfd.fd = fdr;
	pfd.events = POLLOUT;
	if ((res = poll(&pfd, 1, 0)) < 0)
		err(1, "poll");
	printf("fifo opened O_RDONLY polled for POLLOUT return: %s\n",
			decode_events(pfd.revents));

	pfd.fd = fdw;
	pfd.events = POLLIN;
	if ((res = poll(&pfd, 1, 0)) < 0)
		err(1, "poll");
	printf("fifo opened O_WRONLY polled for POLLIN  return: %s\n",
			decode_events(pfd.revents));

	close(fdr);
	close(fdw);
	(void)unlink(FIFONAME);
	return 0;
}


