Note that there are some explanatory texts on larger screens.

plurals
  1. POC++: Implementing Named Pipes using the Win32 API
    text
    copied!<p>I'm trying to implement named pipes in C++, but either my reader isn't reading anything, or my writer isn't writing anything (or both). Here's my reader:</p> <pre><code>int main() { HANDLE pipe = CreateFile(GetPipeName(), GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL); char data[1024]; DWORD numRead = 1; while (numRead &gt;= 0) { ReadFile(pipe, data, 1024, &amp;numRead, NULL); if (numRead &gt; 0) cout &lt;&lt; data; } return 0; } LPCWSTR GetPipeName() { return L"\\\\.\\pipe\\LogPipe"; } </code></pre> <p>And here's my writer:</p> <pre><code>int main() { HANDLE pipe = CreateFile(GetPipeName(), GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL); string message = "Hi"; WriteFile(pipe, message.c_str(), message.length() + 1, NULL, NULL); return 0; } LPCWSTR GetPipeName() { return L"\\\\.\\pipe\\LogPipe"; } </code></pre> <p>Does that look right? numRead in the reader is always 0, for some reason, and it reads nothing but 1024 -54's (some weird I character).</p> <p><strong>Solution:</strong></p> <p>Reader (Server):</p> <pre><code>while (true) { HANDLE pipe = CreateNamedPipe(GetPipeName(), PIPE_ACCESS_INBOUND | PIPE_ACCESS_OUTBOUND , PIPE_WAIT, 1, 1024, 1024, 120 * 1000, NULL); if (pipe == INVALID_HANDLE_VALUE) { cout &lt;&lt; "Error: " &lt;&lt; GetLastError(); } char data[1024]; DWORD numRead; ConnectNamedPipe(pipe, NULL); ReadFile(pipe, data, 1024, &amp;numRead, NULL); if (numRead &gt; 0) cout &lt;&lt; data &lt;&lt; endl; CloseHandle(pipe); } </code></pre> <p>Writer (client):</p> <pre><code>HANDLE pipe = CreateFile(GetPipeName(), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); if (pipe == INVALID_HANDLE_VALUE) { cout &lt;&lt; "Error: " &lt;&lt; GetLastError(); } string message = "Hi"; cout &lt;&lt; message.length(); DWORD numWritten; WriteFile(pipe, message.c_str(), message.length(), &amp;numWritten, NULL); return 0; </code></pre> <p>The server blocks until it gets a connected client, reads what the client writes, and then sets itself up for a new connection, ad infinitum. Thanks for the help, all!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload