/**********************************************************************
 *	ex:se ts=4 sw=4 ai:
 *
 *	Shared Memory Test Program
 *
 *	Author: Gene H. Olson
 *		gene@zeno.mn.org
 *
 *	This is FREE software in the PUBLIC DOMAIN.
 *
 *	"Everything free contains no guarantee."
 *
 ***********************************************************************
 *
 *	This is a throwaway test program and example of how
 *	to use the "share.c" library module.  It is not intended
 *	to be a real program and certainly does not behave like one.
 *
 ***********************************************************************/

#include <stdio.h>
#include <assert.h>
#include <signal.h>

/* @(#)smtest.c	1.4 11/3/90 */

typedef char *opaque ;

extern opaque share_create() ;
extern opaque share_open() ;

#define BS 8096

opaque rsh, wsh ;

quit(sig)
{
	if (wsh) share_close(wsh) ;
	while (wait((int *)0) != -1) ;
	exit(sig) ;
}



main(argc, argv)
int argc ;
char **argv ;
{
	int s ;
	int rcount, wcount ;
	char *rbuf, *wbuf ;
	int rfd[2], wfd[2] ;

	wsh = share_create(rfd, wfd, BS, 100) ;
	assert(wsh) ;

	if (fork() == 0)
	{
		close(1) ;
		close(wfd[0]) ;
		close(wfd[1]) ;

		rsh = share_open(rfd) ;
		assert(rsh) ;

		while (1)
		{
			s = share_get(rsh, &rbuf, &rcount) ;
			if (s <= 0) break ;

			assert(rcount == 0) ;

			rcount = read(0, rbuf, BS) ;
			if (rcount == 0) break ;

			s = share_put(rsh, rbuf, rcount) ;
			if (s <= 0) break ;
		}

		share_close(rsh) ;

		exit(s) ;
	}
	else
	{
		if (signal(SIGHUP, SIG_IGN) != SIG_IGN) signal(SIGHUP, quit) ;
		if (signal(SIGINT, SIG_IGN) != SIG_IGN) signal(SIGINT, quit) ;
		if (signal(SIGQUIT, SIG_IGN) != SIG_IGN) signal(SIGQUIT, quit) ;
		if (signal(SIGPIPE, SIG_IGN) != SIG_IGN) signal(SIGPIPE, quit) ;
		if (signal(SIGTERM, SIG_IGN) != SIG_IGN) signal(SIGTERM, quit) ;

		close(0) ;
		close(rfd[1]) ;

		wsh = share_open(wfd) ;
		assert(wsh) ;

		while (1)
		{
			s = share_get(wsh, &wbuf, &wcount) ;
			if (s <= 0) break ;

			(void) write(1, wbuf, wcount) ;

			(void) share_put(wsh, wbuf, 0) ;
		}

		quit(s) ;
	}
}
