
#ifdef	KSOS
#define	F_ERROR	-1L
#define	F_CHILD	0L
#else	KSOS
#define	F_ERROR	-1
#define	F_CHILD	0
#endif	KSOS

char gfiden[] "TEST2";

char buf[2000];
char ack[3]	"\377\377";

unsigned	int	t_start[2];
unsigned	int	t_end[2];


long	totaltime	0L;
long	totalbytes	0L;
long	limitbytes	0L;

int fds[2];
int fdr[2];

main (argc,argv)
int  argc;
char **argv;
{
	register	int	i;
	register	int	j;
	register	int	k;

	unsigned	int	n;
	unsigned	int	m;

#ifdef	KSOS
	long	pid;
	long	fork ();
#else	KSOS
	int	pid;
#endif	KSOS

	if (argc != 3)
	{
		printf ("Usage:\n\tTEST2 <msg size> <# msgs>\n");
		exit ();
	}
	else
	{
		n = atoi (argv[1]);
		m = atoi (argv[2]);
	}

	printf ("Test 2: Inter-Process Communication (%d msgs, %d bytes/msg)\n",m,n);

	/*
	 * set up sender's path (fds) & receiver's path (fdr)
	 */
	pipe (fds);
	pipe (fdr);

	if ((pid = fork ()) == F_CHILD)
	{
		sleep (5);
		timeon ();
		for (i = 0; i < m; i++)
		{
			if ((k = write (fds[1], buf, n)) != n)
			{
				printf ("Cant write on pipe\n");
				exit ();
			}
			else if (read (fdr[0], ack, 2) != 2)
			{
				printf ("Cant read ack from receiver\n");
				exit ();
			}
			else
			{
				totalbytes += k;
			}
		}
		timeoff ();
		printf ("Test 2: %d messages (%D bytes) sent in %D secs\n", 
			m,
			totalbytes,
			totaltime
		);
		close (fds[1]);
		close (fdr[0]);
		exit ();
	}
	else if (pid != F_ERROR)
	{
		for (i = 0; i < m; i++)
		{
			for (j = n; j > 0; j -= k)
			{
				if ((k = read (fds[0], buf, j)) < 0)
				{
					printf ("Cant read from pipe\n");
					exit ();
				}
				else
				{
					totalbytes += k;
				}
			}

			if (write (fdr[1], ack, 2) != 2)
			{
				printf ("Cant ack to sender\n");
				exit ();
			}
		}
		/*
		printf ("TEST2: received %D bytes\n", totalbytes);
		*/
		exit ();
	}
	else
	{
		printf ("Cant create sending process\n");
		exit ();
	}
}

timeon()
{
	time (t_start);
	printf ("Test 2: Starting ... %s", ctime (t_start));
}

timeoff()
{
	time(t_end);
	totaltime += (32768 * (t_end[0] - t_start[0])) +
			((t_end[1] - t_start[1]));
	printf ("Test 2: Ending ... %s", ctime (t_end));
}

