#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>

char buf[0xffff];

int main() {
	ssize_t nread, nwrite, remains;

	srandom(1); /* Always the same pseudo-random sequence */

	while ( (nread=read(0, buf, 0xfff & rand())) > 0 ) {
		remains = nread;
		while ( remains ) {
			nwrite=write(1, buf, nread);
			if ( nwrite < 0 )  {
				if ( !(errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) ) {
					perror("write");
					return nwrite;
				}
			} else {
				remains -= nwrite;
			}
		}
		/*fprintf(stderr, "nread==%zu, nwrite==%zu\n", nread, nwrite);*/
		usleep( 0xffff & rand() );
	}
	if ( nread < 0 ) {
		perror("read");
		return nread;
	}

	return 0;
}