Skip to content

Commit

Permalink
Fix: Handle ERROR_PIPE_CONNECTED error from ConnectNamedPipe in syelogd
Browse files Browse the repository at this point in the history
Fixes #241

Co-authored-by: fishjam <[email protected]>
  • Loading branch information
fishjam and fishjam authored Jun 30, 2022
1 parent 61c6523 commit a1dd93f
Showing 1 changed file with 29 additions and 18 deletions.
47 changes: 29 additions & 18 deletions samples/syelog/syelogd.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ LONGLONG s_llStartTime = 0;
LONGLONG s_llLastTime = 0;

BOOL LogMessageV(BYTE nSeverity, PCHAR pszMsg, ...);
VOID AcceptAndCreatePipeConnection(PCLIENT pClient, HANDLE hCompletionPort);

//////////////////////////////////////////////////////////////////////////////
//
Expand Down Expand Up @@ -181,8 +182,14 @@ PCLIENT CreatePipeConnection(HANDLE hCompletionPort)
}

if (!ConnectNamedPipe(hPipe, pClient)) {
if (GetLastError() != ERROR_IO_PENDING &&
GetLastError() != ERROR_PIPE_LISTENING) {
DWORD dwLastErr = GetLastError();
//Handle race between multiple client connections
//example: multi thread or client request at alomst same time.
if (ERROR_PIPE_CONNECTED == dwLastErr)
{
AcceptAndCreatePipeConnection(pClient, hCompletionPort);
} else if ( dwLastErr != ERROR_IO_PENDING &&
dwLastErr != ERROR_PIPE_LISTENING) {
MyErrExit("ConnectNamedPipe");
}
}
Expand All @@ -193,6 +200,25 @@ PCLIENT CreatePipeConnection(HANDLE hCompletionPort)
return pClient;
}

VOID AcceptAndCreatePipeConnection(PCLIENT pClient, HANDLE hCompletionPort) {
DWORD nBytes = 0;
InterlockedIncrement(&s_nActiveClients);
pClient->fAwaitingAccept = FALSE;
BOOL b = ReadFile(pClient->hPipe,
&pClient->Message,
sizeof(pClient->Message),
&nBytes,
pClient);
if (!b) {
if (GetLastError() != ERROR_IO_PENDING) {
LogMessageV(SYELOG_SEVERITY_ERROR,
"ReadFile failed %d.", GetLastError());
}
}

CreatePipeConnection(hCompletionPort);
}

BOOL LogMessageV(BYTE nSeverity, PCHAR pszMsg, ...)
{
FILETIME ftOccurance;
Expand Down Expand Up @@ -352,22 +378,7 @@ DWORD WINAPI WorkerThread(LPVOID pvVoid)
}

if (pClient->fAwaitingAccept) {
InterlockedIncrement(&s_nActiveClients);
pClient->fAwaitingAccept = FALSE;
b = ReadFile(pClient->hPipe,
&pClient->Message,
sizeof(pClient->Message),
&nBytes,
pClient);
if (!b) {
if (GetLastError() != ERROR_IO_PENDING) {
LogMessageV(SYELOG_SEVERITY_ERROR,
"ReadFile failed %d.", GetLastError());
continue;
}
}

CreatePipeConnection(hCompletionPort);
AcceptAndCreatePipeConnection(pClient, hCompletionPort);
}
else {
if (nBytes < offsetof(SYELOG_MESSAGE, szMessage)) {
Expand Down

0 comments on commit a1dd93f

Please sign in to comment.