Question

In my program (posted into this question), I have made the following changes at the client end:

wretry:   
   cbToWrite = _stprintf(chBuf[0], TEXT("Message %d from Client"), retrycount - numberofsend + 1);
   cbToWrite *= sizeof(TCHAR);

   fSuccess = WriteFile(hPipe, chBuf[0], cbToWrite,
  &cbWritten, &woverlapped[retrycount-numberofsend]);

By this, now same buffer will be used for writing everytime.

In this case, WriteFile is pending every time as it returns ERROR_IO_PENDING. Since, the content of buffer is overwritten every time, server should receive the last message that was written into the buffer. But server is receiving the messages without any problem.

Does it mean that the message is first copied into some internal buffer? Can I destroy the buffer and expects the message will be delivered to the server?

Was it helpful?

Solution

Again to quote MSDN:

lpBuffer [in] A pointer to the buffer containing the data to be written to the file or device. This buffer must remain valid for the duration of the write operation. The caller must not use this buffer until the write operation is completed.

So it seems your messages are not guaranteed to arrive safely if you mess with the buffer while the write operation is taking place. You should definitely not destroy the buffer

OTHER TIPS

Your code is essentially using undefined behaviour. From the WriteFile documentation:

Accessing the output buffer while a write operation is using the buffer may lead to corruption of the data written from that buffer. Applications must not write to, reallocate, or free the output buffer that a write operation is using until the write operation completes.

As Raymond Chen points out, appearing to succeed is undefined behaviour

Undefined behavior means that anything can happen. The program might crash immediately. It might crash five minutes later. It might send email to your boss saying that you screwed up and then read you Vogon poetry. Or maybe not.

Your code may work right now, but it might just stop working at some point in the future. It could be because you've built in release, or Microsoft changes the underlying workings of WriteFile or random chance.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top