title: WriteFile on a named pipe sometimes returns ERROR_NO_DATA
body: <p>I've got a C++ program that is creating a named pipe to write data to. Some customers have reported a situation where the client connects to the named pipe but the server end fails to write the data (with <code>ERROR_NO_DATA</code>). </p>
  
  <p>This error code isn't really explained in any MSDN page that I could find; does anyone have any ideas on how to fix this? Or what the cause is?</p>
  
  <p><br/></p>
  
  <h2>Open code:</h2>
  
  <pre><code>ostringstream pipeName;
  pipeName &lt;&lt; "\\\\.\\pipe\\unique-named-pipe-" &lt;&lt; GetCurrentProcessId();
  
  pipeHandle = CreateNamedPipeA(
      pipeName.str().c_str(),              // pipe name
      PIPE_ACCESS_DUPLEX,                  // open mode
      PIPE_TYPE_BYTE | PIPE_READMODE_BYTE, // pipe mode
      PIPE_UNLIMITED_INSTANCES,            // max instances
      512,                                 // output buffer size
      512,                                 // input buffer size
      0,                                   // use default timeouts
      NULL);                               // security attributes
  
  if (INVALID_HANDLE_VALUE == pipeHandle)
  {
      THROW("Failed to create named pipe", GetLastError());
  }
  
  cout &lt;&lt; "Pipe ready" &lt;&lt; endl;
  
  // Wait for a client to connect to the pipe        
  BOOL status = ConnectNamedPipe(pipeHandle, NULL);
  
  if (!status)
  {
      DWORD lastError = GetLastError();
  
      if (ERROR_PIPE_CONNECTED != lastError)
      {
          THROW("Failed to wait for client to open pipe", lastError);
      }
      else
      {
          // Ignore, see MSDN docs for ConnectNamedPipe() for details.
      }
  }
  </code></pre>
  
  <p><br/></p>
  
  <h2>Writing code:</h2>
  
  <pre><code>// response is a std::string
  int writeOffset = 0;
  int length = response.length();
  
  while ((int) response.length() &gt; writeOffset)
  {
      DWORD bytesWritten;
  
      BOOL status = WriteFile(
          pipeHandle,
          response.c_str() + writeOffset,
          length - writeOffset,
          &amp;bytesWritten,
          NULL);
  
      if (!status)
      {
          // This sometimes fails with ERROR_NO_DATA, why??
          THROW("Failed to send via named pipe", GetLastError());
      }
  
      writeOffset += bytesWritten;
  }
  </code></pre>
  
  <p><br/></p>
  
  <h2>Throw macro</h2>
  
  <pre><code>#define THROW(message, errorCode) \
  { \
      fprintf(stderr, "%s: line: %d file: %s error:0x%x\n", \
              message, __LINE__, __FILE__, errorCode); \
      fflush(stderr); \
      throw message; \
  } \
  </code></pre>
  
  <p>Thanks!</p>