//bench/bw_door.c
#include	"unpipc.h"

void	reader(int, int);
void	writer(int);
void	server(void *, char *, size_t, door_desc_t *, size_t);

void	*buf;
int		totalnbytes, xfersize, contpipe[2];

int
main(int argc, char **argv)
{
	int		i, nloop, doorfd;
	char	c;
	pid_t	childpid;
	ssize_t	n;

	if (argc != 5)
		err_quit("usage: bw_door <pathname> <#loops> <#mbytes> <#bytes/write>");
	nloop = atoi(argv[2]);
	totalnbytes = atoi(argv[3]) * 1024 * 1024;
	xfersize = atoi(argv[4]);

	buf = Valloc(xfersize);
	Touch(buf, xfersize);

	unlink(argv[1]);
	Close(Open(argv[1], O_CREAT | O_EXCL | O_RDWR, FILE_MODE));
	Pipe(contpipe);		/*     SVR4 */

	if ( (childpid = Fork()) == 0) {
			/*   =  */
		if ( (n = Read(contpipe[0], &c, 1)) != 1)
			err_quit("child: pipe read returned %d", n);
		doorfd = Open(argv[1], O_RDWR);

		writer(doorfd);
		exit(0);
	}
		/*   =  */
	doorfd = Door_create(server, NULL, 0);
	Fattach(doorfd, argv[1]);
	Write(contpipe[1], &c, 1);	/*     */

	Start_time();
	for (i = 0; i < nloop; i++)
		reader(doorfd, totalnbytes);
	printf("bandwidth: %.3f MB/sec\n",
		   totalnbytes / Stop_time() * nloop);
	kill(childpid, SIGTERM);
	unlink(argv[1]);
	exit(0);
}
