The CreateFile function is useful for opening files or devices for read/write access, providing a handle.
The third parameter, dwShareMode, specifies if the file/device can later be accessed by others. An example, with files:
void* pFileHandle1 = ::CreateFileA("C:\\test.txt", GENERIC_READ|GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0);
DWORD lastError = GetLastError(); // 0, ERROR_SUCCESS
void* pFileHandle2 = ::CreateFileA("C:\\test.txt", GENERIC_READ|GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0);
lastError = GetLastError(); // 0, ERROR_SUCCESS
All good here: we have 2 different handles that can read/write a single file.
But in my case, I want to use a COM port:
void* pComHandle1 = ::CreateFileA("\\\\.\\COM3", GENERIC_READ|GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0);
lastError = GetLastError(); // 0, ERROR_SUCCESS
void* pComHandle2 = ::CreateFileA("\\\\.\\COM3", GENERIC_READ|GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0);
lastError = GetLastError(); // 5, ERROR_ACCESS_DENIED Oops!
The first handle is valid and can be used, but the second one is INVALID_HANDLE_VALUE.
What's up with that? Can't you share COM ports that way?
serial!SerialCreateDevObj, it callsIoCreateDevicewithExclusiveas true. The reason for exclusive access is that each application expects exclusive state and settings (e.g. bps, parity). That said, opening the Device returns a handle for a File object, which can be duplicated viaDuplicateHandle. - Eryk Sun\Device\SerialNis exclusive (have flagDO_EXCLUSIVE) device. usually this is FDO device, attached to some PDO. and we can (and really must) open it by PDO interface name, returned byCM_Get_Device_Interface_ListW(&GUID_DEVINTERFACE_COMPORT,..). this PDO not exclusive, but create handler for serial usually allow only single file object opened on device anyway. so you can have multiple handles, but only single file object for serial. - RbMm