write.c 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /*
  2. * Copyright (c) 1993 W. Richard Stevens. All rights reserved.
  3. * Permission to use or modify this software and its documentation only for
  4. * educational purposes and without fee is hereby granted, provided that
  5. * the above copyright notice appear in all copies. The author makes no
  6. * representations about the suitability of this software for any purpose.
  7. * It is provided "as is" without express or implied warranty.
  8. */
  9. #include "sock.h"
  10. #include <sys/uio.h> /* for writev() */
  11. #ifndef UIO_MAXIOV
  12. #define UIO_MAXIOV 16 /* we assume this; may not be true? */
  13. #endif
  14. ssize_t
  15. dowrite(int fd, const void *vptr, size_t nbytes)
  16. {
  17. struct iovec iov[UIO_MAXIOV];
  18. const char *ptr;
  19. int chunksize, i, n, nleft, nwritten, ntotal;
  20. if (chunkwrite == 0 && usewritev == 0)
  21. return(write(fd, vptr, nbytes)); /* common case */
  22. /*
  23. * Figure out what sized chunks to write.
  24. * Try to use UIO_MAXIOV chunks.
  25. */
  26. chunksize = nbytes / UIO_MAXIOV;
  27. if (chunksize <= 0)
  28. chunksize = 1;
  29. else if ((nbytes % UIO_MAXIOV) != 0)
  30. chunksize++;
  31. ptr = vptr;
  32. nleft = nbytes;
  33. for (i = 0; i < UIO_MAXIOV; i++) {
  34. iov[i].iov_base = ptr;
  35. n = (nleft >= chunksize) ? chunksize : nleft;
  36. iov[i].iov_len = n;
  37. if (verbose)
  38. fprintf(stderr, "iov[%2d].iov_base = %x, iov[%2d].iov_len = %d\n",
  39. i, iov[i].iov_base, i, iov[i].iov_len);
  40. ptr += n;
  41. if ((nleft -= n) == 0)
  42. break;
  43. }
  44. if (i == UIO_MAXIOV)
  45. err_quit("i == UIO_MAXIOV");
  46. if (usewritev)
  47. return(writev(fd, iov, i+1));
  48. else {
  49. ntotal = 0;
  50. for (n = 0; n <= i; n++) {
  51. nwritten = write(fd, iov[n].iov_base, iov[n].iov_len);
  52. if (nwritten != iov[n].iov_len)
  53. return(-1);
  54. ntotal += nwritten;
  55. }
  56. return(ntotal);
  57. }
  58. }