0

sendfile()

The offset argument is of type off_t and nbytes is of type size_t while both are describing the same thing: a file length. What if my file is longer than off_t but shorter than size_t? If I'm sending asynchronously it can happen that my current file offset is larger than off_t, but I still want to send more since size_t is greater.

off_t is always lower since it is signed and size_t is unsigned.

I know that you can set nbytes = 0, but I explicitly want to use a length.

Jeff Schaller
  • 66,199
  • 35
  • 114
  • 250

1 Answers1

1

The offset and nbytes arguments are not describing the same thing. On the contrary, they're describing where to start and where to end copying bytes from the file, respectively.

If your file is 131,072 bytes in size (128KiB) and you use an offset of 16,384 and nbytes of 32,768, then sendfile() will copy from position 16,384 to position 49,152 on the file, for a total of 32KiB (specified by nbytes) starting at offset.

If you use an offset of 114,688 and nbytes of 32,768, then sendfile() will copy from position 114,688 to the end of the file, at position 131,072, for a total of 16KiB. Since the file was shorter than the expected nbytes, sendfile() will send less data than requested.

If you use an offset of 147,456 and nbytes of 32,768, then sendfile() will send 0 bytes. If the start is past the end of the file, there will be no bytes to copy, so it will just send nothing.

Finally, there's a special case for nbytes set to 0, which will copy the whole contents of the file, so if you use an offset of 0 and nbytes of 0, then sendfile() will send a total of 131,072 bytes (128KiB), for the whole file.

filbranden
  • 21,113
  • 3
  • 58
  • 84