/*
 *	cswitch: cause context switches as rapidly as possible.
 *
 *
 *	Do this by yoyoing single chracters between two processes over pipes.
 */

#define FROMPIPE 0
#define TOPIPE 1

main()
{
	int ctop[2];		/* pipe from child to parent */
	int ptoc[2];		/* pipe from parent to child */
	int writefd;		/* fd that each process writes to */
	int readfd;		/* fd that each process reads from */
	char ch;		/* the poor little character to yoyo */
	int parent;		/* are we the parent of the two processes? */

	if (pipe(ctop) != 0 || pipe(ptoc) != 0) {
		perror("Cannot create pipe");
		exit(1);
	}

	switch (fork()) {
	case -1:
		perror("Cannot fork");
		exit(1);
	case 0:
		/* child */
		(void) close(ctop[FROMPIPE]);	/* only need to write to this */
		(void) close(ptoc[TOPIPE]);	/* only need to read from */
		writefd = ctop[TOPIPE];
		readfd = ptoc[FROMPIPE];
		parent = 0;
		break;
	default:
		/* parent */
		(void) close(ctop[TOPIPE]);	/* only need to read from */
		(void) close(ptoc[FROMPIPE]);	/* only need to write to */
		writefd = ptoc[TOPIPE];
		readfd = ctop[FROMPIPE];
		parent = 1;

		/* parent can kick things off
		ch = 42;		/* no better value */
		goto writefirst;

		break;
	}

	for (;;) {
		/* receive from pipe */
		if (read(readfd, &ch, 1) != 1) {
			perror("read fails");
			exit(1);
		}
writefirst:
		/* write to pipe */
		if (write(writefd, &ch, 1) != 1) {
			perror("write fails");
			exit(1);
		}
	}
}
