WriteFile 同步(bug)

来源:互联网 发布:知乎周刊 pdf 网盘 编辑:程序博客网 时间:2024/05/18 01:12

真是虐了狗了,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 synchronoushFile parameter. WriteFile sets this value to zero before doing any work or error checking. UseNULL 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 notNULL.

最后一句,仅当参数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);

}

直接用引用,强迫传参。

原创粉丝点击