Advertisement
Snuggledash

bigfilewrite.c

Apr 28th, 2021
690
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.66 KB | None | 0 0
  1. #include <sys/mman.h>
  2. #include <unistd.h>
  3. #include <errno.h>
  4. #include <fcntl.h>
  5. #include <stdio.h>
  6. #include <string.h>
  7. #include <sys/uio.h>
  8. #include <limits.h>
  9.  
  10. // test file with INT_MAX+2 bytes, I used this command to create one:
  11. // % truncate -s 2147483649 garbage.bin              # sparse
  12. // % (openssl rand 2147483647; echo .) > garbage.bin # filled with randomness
  13. #define INFILE "./garbage.bin"
  14.  
  15. //#define WRITESIZE 65536
  16. // size limit for FreeBSD
  17. #define WRITESIZE INT_MAX
  18. //#define WRITESIZE ((size_t)INT_MAX+1)
  19.  
  20. #define MAPSIZE WRITESIZE
  21. //#define MAPSIZE ((size_t)INT_MAX+4097)
  22.  
  23. #define FAIL ret = 1; goto fail
  24.  
  25. static void printerr(const char *what) {
  26.   fprintf(stderr, "%s: %s\n", what, strerror(errno));
  27. }
  28.  
  29. int main(void) {
  30.   void *ptr = NULL;
  31.   int ret = 0;
  32.   int ifd = -1, ofd = -1;
  33.   ssize_t res;
  34.   struct iovec lonevec[1];
  35.  
  36.   ifd = open(INFILE, O_RDONLY);
  37.   if (ifd == -1) {
  38.     printerr("open (in)");
  39.     FAIL;
  40.   }
  41.   ptr = mmap(NULL, MAPSIZE, PROT_READ, MAP_PRIVATE, ifd, 0);
  42.   if (ptr == MAP_FAILED) {
  43.     printerr("mmap");
  44.     FAIL;
  45.   }
  46.   ofd = open("/dev/null", O_WRONLY);
  47.   if (ofd == -1) {
  48.     printerr("open (out)");
  49.     FAIL;
  50.   }
  51.   res = write(ofd, ptr, WRITESIZE);
  52.   if (res == -1) {
  53.     printerr("write");
  54.     ret = 1;
  55.   } else {
  56.     printf("write: %ld\n", res);
  57.   }
  58.   lonevec[0].iov_base = ptr;
  59.   lonevec[0].iov_len = WRITESIZE;
  60.   res = writev(ofd, lonevec, 1);
  61.   if (res == -1) {
  62.     printerr("writev");
  63.     ret = 1;
  64.   } else {
  65.     printf("writev: %ld\n", res);
  66.     ret = 1;
  67.   }
  68.  fail:
  69.   if (ofd >= 0) {
  70.     close(ofd);
  71.     ofd = -1;
  72.   }
  73.   if (ptr) {
  74.     munmap(ptr, MAPSIZE);
  75.     ptr = NULL;
  76.   }
  77.   if (ifd >= 0) {
  78.     close(ifd);
  79.     ifd = -1;
  80.   }
  81.   return ret;
  82. }
  83.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement