[英]Named pipe wait for client in background until client connects
我試圖使我的命名管道服務器跳過ConnectNamedPipe函數的阻塞等待,直到我的客戶端嘗試連接為止。 所以我想讓我的代碼繼續通過ConnetNamedPipe行直到結尾,但要保持我的管道的連接在背景中打開。 如果在創建管道時使用PIPE_NOWAIT模式,它將立即返回,並且在客戶端可以連接之前管道將關閉。
我知道我嘗試使用線程來執行此操作,但是即使創建線程並在線程內執行代碼的ConnectNamedPipe部分,它仍然在此行等待,而不是繼續執行我的代碼。 一旦到達我的服務器cpp文件代碼的末尾,我想用我的客戶端連接到管道。
我的煙斗:
hPipe = CreateNamedPipe(
lpszPipename,
PIPE_ACCESS_OUTBOUND, // one way access, only send data
PIPE_TYPE_MESSAGE | // message type pipe
PIPE_READMODE_MESSAGE | // message-read mode
PIPE_WAIT,
PIPE_UNLIMITED_INSTANCES,
512,
512,
0,
NULL);
if (hPipe == INVALID_HANDLE_VALUE)
{
Out->msg(ERR,"Creating the pipe failed.");
}
// Create a thread for this client.
hThread = CreateThread(
NULL, // no security attribute
0, // default stack size
InstanceThread, // thread proc
(LPVOID) hPipe, // thread parameter
0, // not suspended
&dwThreadId); // returns thread ID
if (hThread == NULL)
{
Out->msg(ERR,"Creating the thread failed.");
}
else CloseHandle(hThread);
// Close the pipe.
CloseHandle(hPipe);
我的主題:
DWORD WINAPI InstanceThread(LPVOID lpvParam)
{
Out->msg(output::SEV_INFO,"Waiting for client to connect.");
fConnected = ConnectNamedPipe(hPipe, NULL) ? //This is where the execution hangs
TRUE : (GetLastError() == ERROR_PIPE_CONNECTED);
HANDLE hHeap = GetProcessHeap();
TCHAR* pchReply = (TCHAR*)HeapAlloc(hHeap, 0, BUFSIZE*sizeof(TCHAR));
DWORD cbBytesRead = 0, cbReplyBytes = 0, cbWritten = 0;
BOOL fSuccess = FALSE;
HANDLE hPipe = NULL;
// The thread's parameter is a handle to a pipe object instance.
hPipe = (HANDLE) lpvParam;
uint32_t startTime = time(NULL);
uint32_t elapsedTime;
// Loop until done reading
while ((elapsedTime < 60))
{
elapsedTime = difftime(time(NULL), startTime);
// Write to the pipe.
fSuccess = WriteFile(
hPipe, // handle to pipe
pchReply, // buffer to write from
cbReplyBytes, // number of bytes to write
&cbWritten, // number of bytes written
NULL); // not overlapped I/O
if (!fSuccess || cbReplyBytes != cbWritten)
{
Out->msg(ERR,"InstanceThread WriteFile failed.");
break;
}
}
// Flush the pipe to allow the client to read the pipe's contents
// before disconnecting. Then disconnect the pipe, and close the
// handle to this pipe instance.
FlushFileBuffers(hPipe);
DisconnectNamedPipe(hPipe);
CloseHandle(hPipe);
HeapFree(hHeap, 0, pchReply);
Out->msg(output::SEV_INFO,"InstanceThread exitting.\n");
return 1;
}
我試圖使我的命名管道服務器跳過ConnectNamedPipe函數的阻塞等待,直到我的客戶端嘗試連接為止。
所以您在談論服務器。
因此,我希望我的代碼繼續通過
ConnectNamedPipe
行,同時仍然能夠連接到我的服務器。
所以您在談論客戶。
這沒有道理。 ConnectNamedPipe()
是一個服務器端函數,除了阻塞直到客戶端連接,您在專用於它的線程中沒有任何有用的事情。 這樣吧。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.