#include <unistd.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <stdio.h>
#include <stdlib.h>
#include <poll.h>
#include <errno.h>
#include <string.h>

static int testpoll(int fd);

int main() {
    int sv[2];
    int i;
    char ch;
    int rv = socketpair(PF_UNIX, SOCK_STREAM, 0, sv);
    if (rv) {
	perror("socketpair");
	return rv;
    }
    rv = fcntl(sv[0], F_GETFL);
    if (rv == -1) {
	perror("getfl");
	return rv;
    }
    rv |= O_NONBLOCK;
    rv = fcntl(sv[0], F_SETFL, (long)rv);
    if (rv == -1) {
	perror("setfl");
	return rv;
    }
    while (write(sv[0], &ch, 1) == 1) 
	i++;
    if (errno == EWOULDBLOCK) {
	printf("Wrote %d bytes to socket before blocking.\n", i);
    } else {
	fprintf(stderr, "write failed (%s) after %d bytes.\n", 
		strerror(errno), i);
	return errno;
    }
    i = 0;
    for (i = 0; !testpoll(sv[0]); i++) {
        rv = read(sv[1], &ch, 1);
        if (rv != 1) {
	    perror("read");
	    return rv;
        }
    }
    printf("poll returned for writing after %d bytes freed\n", i);
    return 0;
}

static int testpoll(int fd) {
    struct pollfd pfd = { fd, POLLOUT, 0 };
    int rv = poll(&pfd, 1, 0);
    if (rv == 0) {
	return 0;
    } else if (rv == 1) {
	return 1;
    } else {
	perror("poll");
	exit(rv);
    }
}
    
