我有一个 C++ 程序,它正在创建一个命名管道来写入数据。有客户反映了客户端连接命名管道但服务器端写入数据失败的情况(用ERROR_NO_DATA
).
我能找到的任何 MSDN 页面都没有真正解释此错误代码;有人对如何解决这个问题有任何想法吗?或者说是什么原因呢?
开放代码:
ostringstream pipeName;
pipeName << "\\\\.\\pipe\\unique-named-pipe-" << 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 << "Pipe ready" << 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.
}
}
编写代码:
// response is a std::string
int writeOffset = 0;
int length = response.length();
while ((int) response.length() > writeOffset)
{
DWORD bytesWritten;
BOOL status = WriteFile(
pipeHandle,
response.c_str() + writeOffset,
length - writeOffset,
&bytesWritten,
NULL);
if (!status)
{
// This sometimes fails with ERROR_NO_DATA, why??
THROW("Failed to send via named pipe", GetLastError());
}
writeOffset += bytesWritten;
}
投掷宏
#define THROW(message, errorCode) \
{ \
fprintf(stderr, "%s: line: %d file: %s error:0x%x\n", \
message, __LINE__, __FILE__, errorCode); \
fflush(stderr); \
throw message; \
} \
Thanks!