exercise_13_2.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /*
  2. Time the operation of the filebuff/write_bytes.c program (provided in the source
  3. code distribution for this book) for various buffer sizes and file systems.
  4. */
  5. /*
  6. ./a.out file 100000000 100 0,38s user 1,16s system 99% cpu 1,542 total
  7. ./a.out file 100000000 1000000 0,00s user 0,05s system 98% cpu 0,053 total
  8. -DUSE_FSYNC -DFUSE_FDATASYNC
  9. ./a.out file 100000000 1000000 0,00s user 0,13s system 16% cpu 0,844 total
  10. */
  11. #include <stdlib.h>
  12. #include <sys/stat.h>
  13. #include <fcntl.h>
  14. #include <unistd.h>
  15. #include <string.h>
  16. #include <tgmath.h>
  17. int
  18. main(int argc, char *argv[])
  19. {
  20. size_t bufSize, numBytes, thisWrite, totWritten;
  21. char *buf;
  22. int fd, openFlags;
  23. if (argc != 4 || strcmp(argv[1], "--help") == 0)
  24. exit(EXIT_FAILURE);
  25. numBytes = atoll(argv[2]);
  26. bufSize = atoll(argv[3]);
  27. buf = malloc(bufSize);
  28. if (buf == NULL)
  29. exit(EXIT_FAILURE);
  30. openFlags = O_CREAT | O_WRONLY;
  31. #if defined(USE_O_SYNC) && defined(O_SYNC)
  32. openFlags |= O_SYNC;
  33. #endif
  34. fd = open(argv[1], openFlags, S_IRUSR | S_IWUSR);
  35. if (fd == -1)
  36. exit(EXIT_FAILURE);
  37. for (totWritten = 0; totWritten < numBytes;
  38. totWritten += thisWrite) {
  39. thisWrite = fmin(bufSize, numBytes - totWritten);
  40. if (write(fd, buf, thisWrite) != thisWrite)
  41. exit(EXIT_FAILURE);
  42. #ifdef USE_FSYNC
  43. if (fsync(fd))
  44. exit(EXIT_FAILURE);
  45. #endif
  46. #ifdef USE_FDATASYNC
  47. if (fdatasync(fd))
  48. exit(EXIT_FAILURE);
  49. #endif
  50. }
  51. if (close(fd) == -1)
  52. exit(EXIT_FAILURE);
  53. return EXIT_SUCCESS;
  54. }