I have a Win32 application that I’m making, and it sends a string from one process to another via a named pipe. However, the process that calls ReadFile on the pipe gets the string with some garbled data in it. It returns the number of bytes written correctly, but the last 8 characters or so of the string are garbled.
Here is the code for creating the pipe, and writing to it:
myPipe = CreateNamedPipe(L'\\\\.\\pipe\\testpipe', PIPE_ACCESS_OUTBOUND, PIPE_NOWAIT, 10, 512, 512, 10, NULL); TCHAR title[128]; GetWindowText(foundHwnd, title, 128); wstring windowTitle(title); vector<wstring> splitVec; boost::split(splitVec, windowTitle, boost::algorithm::is_any_of(wstring(L'|'))); WriteFile(myPipe, splitVec[0].c_str(), splitVec[0].size(), &wrote, NULL);
And here is the code that reads it:
if (WaitNamedPipe(L'\\\\.\\pipe\\testpipe', 5000) == 0) { MessageBox(NULL, L'Unable to wait for pipe', L'Error', MB_OK); return false; } myPipe = CreateFile(L'\\\\.\\pipe\\testpipe', GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (myPipe == INVALID_HANDLE_VALUE) { MessageBox(NULL, L'Unable to open pipe', L'Error', MB_OK); return false; } // Other code here... TCHAR buf[512]; DWORD read; success = ReadFile(myPipe, buf, 512, &read, NULL); if (read > 0) MessageBox(NULL, buf, L'Got Data', MB_OK);
When MessageBox is shown, the end of the string is garbled and I have no idea why. Any ideas?
Thanks!
I think the key here is to make sure that your strings are null terminated and that you send the termination character as well. You shouldn’t have to send the entire buffer if the communications is synchronous or if you set it up in
PIPE_READMODE_MESSAGE. ReadFile will return when either the specified number of bytes has been read or a write operation completes on the other end of the pipe. I believe that the ‘garbled’ text is really garbage in the read buffer on the client side of the pipe and because you are not transmitting the string termination character, it is including this in the text sent to the message box. Either clear your read buffer before sending or send the string termination character with the message and I think it will work without the overhead of sending a full buffer.Here is sample client from MSDN. Note how the client sends exactly the number of characters in the message + 1 (including the termination character) and receives into a fixed buffer of size 512. If you look at a server example, you’ll see the same pattern.