![](/img/trans.png)
[英]WriteFile and ReadFile on child process's stdio (using overlapped named pipe)
[英]WriteFile on a named pipe sometimes returns ERROR_NO_DATA
我有一個 C++ 程序,它正在創建一個名為 pipe 來寫入數據。 有客戶反映客戶端連接到名為 pipe 但服務端寫入數據失敗(帶有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; \
} \
謝謝!
查看 WinError.h,這是定義此錯誤代碼和其他錯誤代碼的位置:
//
// MessageId: ERROR_NO_DATA
//
// MessageText:
//
// The pipe is being closed.
//
#define ERROR_NO_DATA 232L
聽起來客戶端已經關閉了 pipe 的結尾 - 也許客戶端代碼認為它已經獲得了完整的字符串,關閉了結尾,而上面的代碼繼續嘗試編寫?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.