1

I'm calling WriteFile to send data to a modem:

BOOL writeResult = WriteFile(m_hPort, p_message, length, &numOut, NULL);

where:

  • m_hPort is a valid HANDLE
  • p_message is an unsigned char* containing ate0\r
  • length is an int with a value of 5
  • numOut is an unsigned long initialised to 0

Occasionally I'm seeing this method succeed but numOut != length

How is it possible for WriteFile to return success without sending any data?

Edit This is how I'm creating the handle:

HANDLE hPort = CreateFileA("\\\\.\\COM5", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);

I've checked the return and it's not INVALID_HANDLE_VALUE which suggests it's valid.

Jon Cage
  • 36,366
  • 38
  • 137
  • 215
  • so `numOut` is `0` or something else? – Andriy Tylychko Feb 24 '12 at 10:01
  • This is entirely determined by the serial port driver. The *normal* way is for it to block the call until enough space is left in the transmit buffer to fit the data. But unfortunately there are a lot of crappy drivers out there, particularly the kind that emulate a serial port for a BlueTooth or USB device. Trial and error stuff. Do pay attention to SetCommTimeouts(). – Hans Passant Feb 24 '12 at 11:00
  • As it happens I am indeed going through an EasySync USB<->Serial converter: http://www.easysync-ltd.com/product/532/es-u-1101-m.html ...so perhaps that's the culprit. – Jon Cage Feb 24 '12 at 11:03

2 Answers2

1

The documentation states:

When writing to a non-blocking, byte-mode pipe handle with insufficient buffer space, WriteFile returns TRUE with *lpNumberOfBytesWritten < nNumberOfBytesToWrite.

Could it be that the modem has a similar behavior when you send data faster than can be transmitted?

gae123
  • 8,589
  • 3
  • 35
  • 40
  • Interesting - you may be onto something there. Is there any way to check how much buffer space is possible / available? – Jon Cage Feb 24 '12 at 10:44
1

Turned out to be a hardware issue after all.

Power cycling the converter would clear the hardware buffer leading us to suspect that it was a problem with the drivers for that device. From Hans' suggestion we dropped the timeouts and then started probing the error reports in more detail.

Reducing the timeout to something sensible meant we were able to identify that the buffers were filling up until they cannae' take nae' more! Which is why power cycling the converter fixed it (we tried re-routing power through engineering and reversing the polarity, but unusually, neither resolved the issue).

The root cause was some flaky hardware flow control causing the software to block indefinitely. Disabling the flow control solved the issue.

Jon Cage
  • 36,366
  • 38
  • 137
  • 215