Writing synchronously to a file opened with FILE_FLAG_OVERLAPPED

泪湿孤枕 提交于 2019-12-10 20:57:22

问题


I have opened a file using

HANDLE handle= 
    CreateFileW(
        fileName, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 
        FILE_FLAG_OVERLAPPED, NULL);

The file handle is then used for asynchronous read operations:

ReadFile(handle, buffer, 1, NULL, &overlapped);

This works. However, I want to do a synchronous write now. WriteFile documentation states that

If hFile was opened with FILE_FLAG_OVERLAPPED, the following conditions are in effect:
• The lpOverlapped parameter must point to a valid and unique OVERLAPPED structure, otherwise the function can incorrectly report that the write operation is complete.

When the lpOverlapepd parameter is omitted, ERROR_INVALID_PARAMETER is returned by GetLastError(). Opening two handles, one for reading and one for writing does also not work since the second handle produces a ERROR_ACCESS_DENIED error.

How can I open the file for asynchronous reads and synchronous writes? I don't want to increase code complexity unnecessarily.


回答1:


Synchronous writes can be achieved by creating a manual reset event for the write operation, writing to the file (using the event in the overlapped structure for your write operation) and then immediately waiting for the event.

Depending on whether your asynchronous read needs to be asynchronous with your write, you may need to make sure you use a compatible wait so that your read completion routine can be called otherwise the read will take place and the data will be stored in the buffer but you cannot process it.




回答2:


Open two handles, one for async read the other for sync write, just make sure that you set the file share attributes (FILE_SHARE_READ|FILE_SHARE_WRITE). Haven't tested it.



来源:https://stackoverflow.com/questions/6663600/writing-synchronously-to-a-file-opened-with-file-flag-overlapped

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!