CreateFile() takes a long time (~5 seconds) to fail on COM ports already exclusively locked/opened by another program

Paul Daniels 5 Reputation points
2024-07-03T13:10:07.55+00:00

Good day,

I'm writing a program ( well, have written, and it's working fine ), and part of the startup is to scan the available COM ports to see which one our device is connected to.

It all works fine except that on some devices there can be a ~5 second delay before CreateFile() fails with INVALID_HANDLE_VALUE because the COM port is already being accessed --- the failure is correct, but what I'm trying to do is reduce the 5 second wait to as little as possible, otherwise our program seems to just stall from the customer's perspective.

Below is the code used to attempt to open the COM port for each possible COM port is found in the system.

To reiterate, the code works correctly, I was just hoping to have CreateFile() return with the fault code quicker than the ~5 seconds.

	BOOL com_read_status;  // return status of various com port functions
	/*
	 * Open the serial port
	 */
	pg->hComm = CreateFile(com_port,      // Name of port
			GENERIC_READ,
			0,             // No Sharing
			0,          // No Security
			OPEN_EXISTING, // Open existing port only
			0,             // no overlapped I/O
			0);         // Null/0 for comm devices
	/*
	 * Check the outcome of the attempt to create the handle for the com port
	 */
	if (pg->hComm == INVALID_HANDLE_VALUE) {
		flog("Failure in opening port\r\n");
		return 1;
	} else {
		flog("Success in opening port\r\n");
	}
Windows API - Win32
Windows API - Win32
A core set of Windows application programming interfaces (APIs) for desktop and server applications. Previously known as Win32 API.
2,651 questions
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.