/*
 * Copyright (c) 2004 Sendmail, Inc. and its suppliers.
 *      All rights reserved.
 *
 * By using this file, you agree to the terms and conditions set
 * forth in the LICENSE file which can be found at the top level of
 * the sendmail distribution.
 *
 * $Id: testfileops.c,v 1.2 2004/10/01 22:12:21 ca Exp $
 */

#include <stdarg.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include <time.h>
#include <errno.h>

static void
msg_fatal(const char *fmt, ...)
{
	va_list ap;

	va_start(ap, fmt);
	vfprintf(stderr, fmt, ap);
	fprintf(stderr, "\n");
	va_end(ap);
	exit(1);
}

static void
fileops(const char *fn, int size, int reps)
{
	ssize_t   s;
	int	 fd, i;
	char	*buf;
	time_t  start, elapsed;
	char	path[BUFSIZ];

	buf = malloc(size);
	if (buf == NULL)
		msg_fatal("buf: %d", errno);
	for (i = 0; i < size; i++)
		buf[i] = i % 32 + ' ';

	snprintf(path, sizeof path, "%s", fn);
	if ((fd = open(path, O_RDWR|O_CREAT|O_TRUNC)) == -1)
		msg_fatal("fopen: %d", errno);
	start = time((time_t *) 0);
	for (i = 0; i < reps; i++)
	{
		if (lseek(fd, 0L, SEEK_SET) != 0)
			msg_fatal("seek: %d", errno);
		if ((s = write(fd, buf, size)) != size)
			msg_fatal("write: %ld, %d", (long) s, errno);
		if (fsync(fd))
			msg_fatal("sync: %d", errno);
	}
	if (close(fd))
		msg_fatal("close: %d", errno);
	elapsed = time((time_t *) 0) - start;
	printf("elapsed time: %ld\n", (long) elapsed);
	if (elapsed == 0)
		elapsed = 1;
	printf("ops: %ld\n", (long) reps / elapsed);
}

static void
usage(const char *prg)
{
	exit(-1);
}

int
main(int argc, char **argv)
{
	int ch;
	int size = 256;
	int op_count = 100;

	while ((ch = getopt(argc, argv, "r:s:")) != EOF)
	{
		switch (ch)
		{
		  case 'r':
			if ((op_count = atoi(optarg)) <= 0)
				usage(argv[0]);
			break;
		  case 's':
			if ((size = atoi(optarg)) <= 0)
				usage(argv[0]);
			break;
		  default:
			usage(argv[0]);
			return -1;
		}
	}

	/* Simulate arrival and delivery of mail messages. */

	fileops("fops", size, op_count);
	return (0);
}


syntax highlighted by Code2HTML, v. 0.9.1