#! /usr/bin/perl

use strict;
use warnings;

use FileHandle;
use File::Sync;

my $M = 10000;
my $N = 5;
my $S = 1024**2;
my $T = 16384;

my $buf = 'x' x $S;
my $fhs = [];

for (my $i = 0; $i < $N; ++$i) {
  $fhs->[$i] = FileHandle->new();
  open $fhs->[$i], '>', "tmp_data_$i.dat"
      or die "Failed to open output file: $!\n";
  syswrite $fhs->[$i], $buf
      or die "Initial write failed: $!\n";
}

for (my $j = 0; $j < $M/$N; ++$j) {
  for (my $i = 0; $i < $N; ++$i) {
    my $off = $T*int(rand()*$S/$T);
    my $dat = chr($j % 256) x $T;
    seek $fhs->[$i], $off, 0
        or die "Failed seek: $!\n";
    syswrite $fhs->[$i], $dat, $T
        or die "Failed data write: $!\n";
    File::Sync::fdatasync($fhs->[$i])
        or die "Failed fdatasync: $!\n";
  }
}

for (my $i = 0; $i < $N; ++$i) {
  close $fhs->[$i]
}
