I'm pulling my hair trying to figure out when a serial port finishes closing so I can reopen it. It turns out that CloseHandle()
returns before the port is actually unlocked.
I am opening a serial port using CreateFile(FILE_FLAG_OVERLAPPED)
, associating it with a CompletionPort using CreateIoCompletionPort()
, reading/writing to it using ReadFile()
, WriteFile()
and closing it using CloseHandle()
.
I've noticed that if I close and reopen a serial port quickly enough, I get an ERROR_ACCESS_DENIED
back from CreateFile()
. This is happening in spite of the fact that I'm waiting for CloseHandle()
to return, then waiting for all outstanding read/write operations associated with that handle to come back from the completion port. Surely there is a better way :)
How do I close a serial port synchronously? Please no retry loops, sleep() or some other cheap hacks.
EDIT: Maybe this has something to do with my use of completion ports and FILE_FLAG_OVERLAPPED. I get a callback when the read/write operations complete. Is there some sort of callback for the port closing?
DuplicateHandle
anywhere? – BedwellReadFileEx
andWriteFileEx
. That's also simpler, because APCs only run then the thread enters an alertable wait, so no cross-thread synchronization issues (just be careful about re-entrancy). – BedwellDuplicateHandle
anywhere. – Hadsall