#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/select.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

int
main()
{
	int fd[2];
	pid_t pid;

	if (pipe(fd) < 0) {
		perror("pipe");
		return EXIT_FAILURE;
	}
	
	pid = fork();
	if (pid < 0) {
		perror("fork");
		return EXIT_FAILURE;
	} else if (pid == 0) {
		close(fd[1]);
		printf("child hello\n");
		sleep(1);
		printf("child goodbye\n");
	} else {
		char buf;

		/* parent waits until the pipe is writable */
		close(fd[0]);	/* close read end */
		sleep(2);
		printf("parent select...\n");
		for (;;) {
			fd_set writefds;

			FD_ZERO(&writefds);
			FD_SET(fd[1], &writefds);

			if (select(fd[1] + 1, NULL, &writefds, NULL, NULL) < 0) {
				if (errno != EINTR) {
					perror("select");
					return EXIT_FAILURE;
				}
				continue;
			}
			if (FD_ISSET(fd[1], &writefds))
				break;
		}
		printf("parent sees writable\n");
	}
}
