Skip to content

Commit a1dd93f

Browse files
fishjamfishjam
andauthored
Fix: Handle ERROR_PIPE_CONNECTED error from ConnectNamedPipe in syelogd
Fixes microsoft#241 Co-authored-by: fishjam <[email protected]>
1 parent 61c6523 commit a1dd93f

File tree

1 file changed

+29
-18
lines changed

1 file changed

+29
-18
lines changed

samples/syelog/syelogd.cpp

Lines changed: 29 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ LONGLONG s_llStartTime = 0;
5050
LONGLONG s_llLastTime = 0;
5151

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

5455
//////////////////////////////////////////////////////////////////////////////
5556
//
@@ -181,8 +182,14 @@ PCLIENT CreatePipeConnection(HANDLE hCompletionPort)
181182
}
182183

183184
if (!ConnectNamedPipe(hPipe, pClient)) {
184-
if (GetLastError() != ERROR_IO_PENDING &&
185-
GetLastError() != ERROR_PIPE_LISTENING) {
185+
DWORD dwLastErr = GetLastError();
186+
//Handle race between multiple client connections
187+
//example: multi thread or client request at alomst same time.
188+
if (ERROR_PIPE_CONNECTED == dwLastErr)
189+
{
190+
AcceptAndCreatePipeConnection(pClient, hCompletionPort);
191+
} else if ( dwLastErr != ERROR_IO_PENDING &&
192+
dwLastErr != ERROR_PIPE_LISTENING) {
186193
MyErrExit("ConnectNamedPipe");
187194
}
188195
}
@@ -193,6 +200,25 @@ PCLIENT CreatePipeConnection(HANDLE hCompletionPort)
193200
return pClient;
194201
}
195202

203+
VOID AcceptAndCreatePipeConnection(PCLIENT pClient, HANDLE hCompletionPort) {
204+
DWORD nBytes = 0;
205+
InterlockedIncrement(&s_nActiveClients);
206+
pClient->fAwaitingAccept = FALSE;
207+
BOOL b = ReadFile(pClient->hPipe,
208+
&pClient->Message,
209+
sizeof(pClient->Message),
210+
&nBytes,
211+
pClient);
212+
if (!b) {
213+
if (GetLastError() != ERROR_IO_PENDING) {
214+
LogMessageV(SYELOG_SEVERITY_ERROR,
215+
"ReadFile failed %d.", GetLastError());
216+
}
217+
}
218+
219+
CreatePipeConnection(hCompletionPort);
220+
}
221+
196222
BOOL LogMessageV(BYTE nSeverity, PCHAR pszMsg, ...)
197223
{
198224
FILETIME ftOccurance;
@@ -352,22 +378,7 @@ DWORD WINAPI WorkerThread(LPVOID pvVoid)
352378
}
353379

354380
if (pClient->fAwaitingAccept) {
355-
InterlockedIncrement(&s_nActiveClients);
356-
pClient->fAwaitingAccept = FALSE;
357-
b = ReadFile(pClient->hPipe,
358-
&pClient->Message,
359-
sizeof(pClient->Message),
360-
&nBytes,
361-
pClient);
362-
if (!b) {
363-
if (GetLastError() != ERROR_IO_PENDING) {
364-
LogMessageV(SYELOG_SEVERITY_ERROR,
365-
"ReadFile failed %d.", GetLastError());
366-
continue;
367-
}
368-
}
369-
370-
CreatePipeConnection(hCompletionPort);
381+
AcceptAndCreatePipeConnection(pClient, hCompletionPort);
371382
}
372383
else {
373384
if (nBytes < offsetof(SYELOG_MESSAGE, szMessage)) {

0 commit comments

Comments
 (0)