uv_fs_read与uv_fs_write的-1偏移参数含义及文档矛盾疑问
-1 Offset in uv_fs_read and uv_fs_write Great question—this is a common point of confusion thanks to the subtle gap between libuv's documented equivalence to system calls and its actual internal behavior. Let's break this down clearly:
1. The Docs vs. Libuv's Hidden Exception
The libuv docs state uv_fs_read is equivalent to preadv(2) and uv_fs_write to pwritev(2), which holds true for most cases—but there's a critical carveout for the -1 offset value.
While preadv(2) and pwritev(2) do throw an EINVAL error for negative offsets, libuv doesn't invoke these system calls when you pass -1. Instead, it falls back to the standard readv(2) and writev(2) calls under the hood.
2. What -1 Actually Does
When you pass -1 as the offset to these libuv functions:
- The operation uses the current file pointer position of the target file descriptor (just like regular
read/writecalls). - After the read/write completes, the file pointer is automatically updated to point to the byte immediately after the last one processed.
This is exactly why the uvbook example works for implementing cat: it enables sequential reading of the file from start to finish, with the pointer advancing naturally with each call—perfect for streaming the entire file content.
3. The Reason for This Abstraction
Libuv builds this flexibility into its API to offer a unified interface for different file access patterns:
- Use a positive offset to perform fixed-position reads/writes (matching
preadv/pwritevbehavior). - Use
-1to perform sequential reads/writes (matching standardreadv/writevbehavior).
This avoids forcing developers to switch between separate functions depending on whether they need to work with a fixed position or the current file pointer.
内容的提问来源于stack exchange,提问作者user6872780

