开发者

WriteFile function's lpNumberOfBytesWritten parameter

开发者 https://www.devze.com 2023-03-16 01:27 出处:网络
MSDN says, When writing to a non-blocking, byte-mode pipe handle with insufficient buffer space, WriteFile returns TRUE with *lpNumberOfBytesWritten < nNumberOfBytesToWrite.

MSDN says,

When writing to a non-blocking, byte-mode pipe handle with insufficient buffer space, WriteFile returns TRUE with *lpNumberOfBytesWritten < nNumberOfBytesToWrite.

For a file or a socket(not pipe), can *lpNumberOfBytesWritten le开发者_StackOverflow社区ss than nNumberOfBytesToWrite(and the result is TRUE) when I call the function synchronously.

If so, why(and when) does the correspond driver complete the IRP like that?

When I see below code, I always worry about "what if *lpNumberOfBytesWritten < BytesToWrite?"

BOOL fOk = WriteFile(hFileOrSocket, ...); // Synchronously
if (fOk)
{
  // It assumes everything is fine
}

Don't I need to worry about that?


AFAIK if the file handle is opened for a synchronous write - the situation you describe (*lpNumberOfBytesWritten < BytesToWritten) will never happen.

The whole point in partial write is to give you an opportunity to write a portion of your data before failing with error such as WSAEWOULDBLOCK or similar. The asynchronous I/O model says write as much as you can until you get an appropriate error, and then wait until some of the I/Os are completed.

Not to be confused with the overlapped I/O. There you schedule I/O and it completes asynchronously (by the underlying driver).


"For a file or a socket(not pipe),"

For a file it ought to be pretty easy to imagine.

It's easy to experiment too. Create a hard disk partition of size 100 MB, open a file, write 99 MB, and then try to write another 99 MB. The experiment might not be reliable because some version of Windows might return FALSE, but it's easy to imagine that some other version of Windows might return TRUE with *lpNumberOfBytesWritten less than nNumberOfBytesToWrite.

0

精彩评论

暂无评论...
验证码 换一张
取 消