#include <unistd.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
#include <stdio.h>

#define BUFLEN 4096
#define FILENAME ".file-ping"

float interval(struct timeval start, struct timeval end) {
  return (end.tv_sec - start.tv_sec) + (end.tv_usec - start.tv_usec)/1000000.0;
}

void ping() {
  char printstring[BUFLEN];
  int fd;
  struct timeval start, end;

  memset(printstring, 'x', BUFLEN);
  fd = open(FILENAME,O_CREAT|O_EXCL|O_WRONLY,S_IRUSR|S_IWUSR);
  if(fd < 0) {
    fprintf(stderr,"open failed: %s\n", strerror(errno));
    return;
  }

  if(unlink(FILENAME) < 0) {
    fprintf(stderr,"unlink failed: %s\n", strerror(errno));
    return;
  }

  gettimeofday(&start,NULL);

  if(write(fd,printstring,BUFLEN) < 0) {
    fprintf(stderr,"write failed: %s\n", strerror(errno));
    return;
  }

  if(fsync(fd) < 0) {
    fprintf(stderr,"fsync failed: %s\n", strerror(errno));
    return;
  }

  close(fd);

  gettimeofday(&end,NULL);

  printf("took %fs\n",interval(start,end));
}

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

  for(i = 0; i < 10; i++) {
    ping();
    sleep(1);
  }
}
