I'm trying to do 'pre-flight checks' by testing a COM port's 'openability' before launching a dialog window which allows the user to do com-porty things.
Here's the code sequence, in outline:
handle = CreateFile("\\\\.\\COM4:", GENERIC_READ | GENERIC_WRITE, 0,NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED,NULL);
if (handle != INVALID_HANDLE_VALUE)
{
CloseHandle(handle);
DoTheWork("\\\\.\\COM4:");
}
else
{
ShowMessage("I'm sorry Dave, I can't do that");
}
...
void DoTheWork(char * port)
{
handle = CreateFile(port, GENERIC_READ | GENERIC_WRITE, 0,NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED,NULL);
/// do lots of stuff
CloseHandle(port);
}
Here's the problem: "DoTheWork" is a tried and tested function, and performs correctly on it's own. It only fails when called immediately after the earlier CreateFile/CloseHandle calls, when the second CreateFile returns E_ACCESSDENIED.
Worse yet, if I step through the code slowly in the debugger, It works just fine.
It seems like I need a Sleep() after the first closeHandle, but that feels like a hack - and i have no way of knowing how long it must be.