I have a device that sends data to COM port. And I'd like to simulate this device when it's not plugged in. I thought that this can be accomplished by simply sending data to a specific COM port:
int main() {
char *port = "\\\\.\\COM40";
HANDLE hCom = CreateFile(port, GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
if (hCom==INVALID_HANDLE_VALUE) return 0;
DWORD writeBytes;
int buffer = 0xDEADBEAF;
BOOL success = WriteFile(hCom, &buffer, 4, &writeBytes, NULL);
FlushFileBuffers(hCom);
Sleep(1000);
HANDLE hCom2 = CreateFile(port, GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
if (hCom2==INVALID_HANDLE_VALUE) return 0; // Exit. GetLastError() == 5
DWORD readBytes;
success = ReadFile(hCom2, &buffer, 4, &readBytes, NULL);
CloseHandle(hCom);
CloseHandle(hCom2);
return 0;
}
Unfortunately that doesn't work and second CreateFile()
sets last error to ERROR_ACCESS_DENIED
.
What am I missing?