【发布时间】:2011-02-08 02:21:22
【问题描述】:
我正在尝试在 C++ 中实现命名管道,但是我的读者没有阅读任何内容,或者我的作者没有写任何内容(或两者兼而有之)。这是我的读者:
int main()
{
HANDLE pipe = CreateFile(GetPipeName(), GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);
char data[1024];
DWORD numRead = 1;
while (numRead >= 0)
{
ReadFile(pipe, data, 1024, &numRead, NULL);
if (numRead > 0)
cout << data;
}
return 0;
}
LPCWSTR GetPipeName()
{
return L"\\\\.\\pipe\\LogPipe";
}
这是我的作者:
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";
}
看起来对吗?由于某种原因,阅读器中的 numRead 始终为 0,它只读取 1024 -54(一些奇怪的 I 字符)。
解决方案:
阅读器(服务器):
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 << "Error: " << GetLastError();
}
char data[1024];
DWORD numRead;
ConnectNamedPipe(pipe, NULL);
ReadFile(pipe, data, 1024, &numRead, NULL);
if (numRead > 0)
cout << data << endl;
CloseHandle(pipe);
}
作家(客户):
HANDLE pipe = CreateFile(GetPipeName(), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
if (pipe == INVALID_HANDLE_VALUE)
{
cout << "Error: " << GetLastError();
}
string message = "Hi";
cout << message.length();
DWORD numWritten;
WriteFile(pipe, message.c_str(), message.length(), &numWritten, NULL);
return 0;
服务器一直阻塞,直到它获得连接的客户端,读取客户端写入的内容,然后无限期地为新连接设置自己。谢谢大家的帮助!
【问题讨论】:
-
您应该在对管道句柄进行操作之前断言它们是有效的。一般来说,代码中的一些更健壮性将大大有助于您发现和调试问题。
-
检查ReadFile/WriteLine的结果是否为
TRUE。可能是读/写的时候出错了,比如管道无效。 -
检查HANDLE是否有效,然后使用GetLastError和WriteFile的输出
-
您可能想标记此 Windows 或 win32。
-
这个也是一个很好的例子。 stackoverflow.com/a/1851489/1961554
标签: c++ windows winapi named-pipes