#include <sys_defs.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <msg.h>
#include <msg_vstream.h>
static void rename_file(int old, int new)
{
char new_path[BUFSIZ];
char old_path[BUFSIZ];
sprintf(new_path, "%06d", new);
sprintf(old_path, "%06d", old);
if (rename(old_path, new_path))
msg_fatal("rename %s to %s: %m", old_path, new_path);
}
static void make_file(int seqno, int size)
{
char path[BUFSIZ];
char buf[1024];
FILE *fp;
int i;
sprintf(path, "%06d", seqno);
if ((fp = fopen(path, "w")) == 0)
msg_fatal("open %s: %m", path);
memset(buf, 'x', sizeof(buf));
for (i = 0; i < size; i++)
if (fwrite(buf, 1, sizeof(buf), fp) != sizeof(buf))
msg_fatal("fwrite: %m");
if (fsync(fileno(fp)))
msg_fatal("fsync: %m");
if (fclose(fp))
msg_fatal("fclose: %m");
if ((fp = fopen(path, "r")) == 0)
msg_fatal("open %s: %m", path);
while (fgets(path, sizeof(path), fp))
;
if (fclose(fp))
msg_fatal("fclose: %m");
}
static void use_file(int seqno)
{
char path[BUFSIZ];
FILE *fp;
int i;
sprintf(path, "%06d", seqno);
if ((fp = fopen(path, "w")) == 0)
msg_fatal("open %s: %m", path);
for (i = 0; i < 400; i++)
fprintf(fp, "hello");
if (fsync(fileno(fp)))
msg_fatal("fsync: %m");
if (fclose(fp))
msg_fatal("fclose: %m");
if ((fp = fopen(path, "r+")) == 0)
msg_fatal("open %s: %m", path);
while (fgets(path, sizeof(path), fp))
;
if (ftruncate(fileno(fp), (off_t) 0))
msg_fatal("ftruncate: %m");;
if (fclose(fp))
msg_fatal("fclose: %m");
}
static void remove_file(int seq)
{
char path[BUFSIZ];
sprintf(path, "%06d", seq);
if (remove(path))
msg_fatal("remove %s: %m", path);
}
static void remove_silent(int seq)
{
char path[BUFSIZ];
sprintf(path, "%06d", seq);
(void) remove(path);
}
static void usage(char *myname)
{
msg_fatal("usage: %s [-cr] [-s size] messages directory_entries", myname);
}
int main(int argc, char **argv)
{
int op_count;
int max_file;
time_t start;
int do_rename = 0;
int do_create = 0;
int seq;
int ch;
int size = 2;
msg_vstream_init(argv[0], VSTREAM_ERR);
while ((ch = GETOPT(argc, argv, "crs:")) != EOF) {
switch (ch) {
case 'c':
do_create++;
break;
case 'r':
do_rename++;
break;
case 's':
if ((size = atoi(optarg)) <= 0)
usage(argv[0]);
break;
default:
usage(argv[0]);
}
}
if (argc - optind != 2 || (do_rename && !do_create))
usage(argv[0]);
if ((op_count = atoi(argv[optind])) <= 0)
usage(argv[0]);
if ((max_file = atoi(argv[optind + 1])) <= 0)
usage(argv[0]);
for (seq = 0; seq < max_file; seq++)
make_file(seq, size);
start = time((time_t *) 0);
while (op_count > 0) {
seq %= max_file;
if (do_create) {
remove_file(seq);
make_file(seq, size);
if (do_rename) {
rename_file(seq, seq + max_file);
rename_file(seq + max_file, seq);
}
} else {
use_file(seq);
}
seq++;
op_count--;
}
printf("elapsed time: %ld\n", (long) time((time_t *) 0) - start);
for (seq = 0; seq < max_file; seq++)
remove_silent(seq);
return (0);
}