WriteFile 同步(bug)

真是虐了狗了,windows10上运行好好的,windows7竟然挂点了。同事,还跟我说,要挂也window10上挂吧,怎么在windows7上挂了尼。

卧槽,经过排查,发现是WriteFile的问题。

函数原型:

BOOL WINAPI WriteFile( HANDLE hFile,LPCVOID lpBuffer,DWORD nNumberOfBytesToWrite, LPDWORD  lpNumberOfBytesWritten,LPOVERLAPPED lpOverlapped);

我这里,只分析lpOverlapped 和 lpNumberOfBytesWriteen 这两个参数,具体使用看msdn;

因为,我是同步执行 所以lpOverlapped传递的nullptr; 其实在使用这个函数的时候,就考虑过 使用lpNumberOfBytesWritten.但后来想想,既然写文件出错了,大多数是系统问题了,所以,传递了一个nullptr, 正是因为lpNumberOfBytesWritten 传递了nullptr,导致程序崩溃,不应该啊微软。但在 windows10上,微软修复了这个问题。

好吧,我们看看msdn是怎么解释这个参数的:

lpNumberOfBytesWritten [out, optional]

A pointer to the variable that receives the number of bytes written when using a synchronous hFile parameter. WriteFile sets this value to zero before doing any work or error checking. Use NULL for this parameter if this is an asynchronous operation to avoid potentially erroneous results.

This parameter can be NULL only when the lpOverlapped parameter is not NULL.

扫描二维码关注公众号,回复: 1765015 查看本文章

最后一句,仅当参数lpOverlapped不为null的时候(异步操作),lpNumberOfBytesWritten才能为null;

因为我使用的是同步写,所以把lpOverlapped传递了null,而我又把lpNumberOfBytesWritten传递为null,所以当往*lpNumberOfBytesWritten写数据的时候,程序崩溃了

所以我包装了这个函数:

inline BOOL SynWriteFile(HANDLE hFile,LPCVOID lpBuffer,DWORD nNumberOfBytesToWrite,DWORD& refNumberOfBytesWritten)

{

                return ::WriteFile(hFile,lpBuffer,nNumberOfBytesToWrite,(LPDWORD)&refNumberOfBytesWritten,nullptr);

}

直接用引用,强迫传参。

猜你喜欢

转载自blog.csdn.net/huanongying131/article/details/78564548