Skip to content

Instantly share code, notes, and snippets.

@lestera
Last active July 10, 2017 06:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lestera/9b6571efe0f7ce617b578c38fdbd507c to your computer and use it in GitHub Desktop.
Save lestera/9b6571efe0f7ce617b578c38fdbd507c to your computer and use it in GitHub Desktop.
HANDLE CreateNewPipe(LPCWSTR lpszPipename);
int _tmain(VOID)
{
BOOL fConnected = FALSE;
DWORD dwThreadId = 0;
HANDLE hPipe = INVALID_HANDLE_VALUE, hThread = NULL;
LPTSTR lpszPipename = TEXT("\\\\.\\pipe\\mynamedpipe");
// The main loop creates an instance of the named pipe and
// then waits for a client to connect to it. When the client
// connects, a thread is created to handle communications
// with that client, and this loop is free to wait for the
// next client connect request. It is an infinite loop.
hPipe = CreateNewPipe(lpszPipename);
for (;;)
{
_tprintf(TEXT("\nPipe Server: Main thread awaiting client connection on %s\n"), lpszPipename);
if (hPipe == INVALID_HANDLE_VALUE)
{
_tprintf(TEXT("CreateNamedPipe failed, GLE=%d.\n"), GetLastError());
return -1;
}
// Wait for the client to connect; if it succeeds,
// the function returns a nonzero value. If the function
// returns zero, GetLastError returns ERROR_PIPE_CONNECTED.
fConnected = ConnectNamedPipe(hPipe, NULL) ?
TRUE : (GetLastError() == ERROR_PIPE_CONNECTED);
if (fConnected)
{
printf("Client connected, creating a processing thread.\n");
HANDLE hPipeForThread = hPipe;
hPipe = CreateNewPipe(lpszPipename);
// Create a thread for this client.
hThread = CreateThread(
NULL, // no security attribute
0, // default stack size
InstanceThread, // thread proc
(LPVOID)hPipeForThread, // thread parameter
0, // not suspended
&dwThreadId); // returns thread ID
if (hThread == NULL)
{
_tprintf(TEXT("CreateThread failed, GLE=%d.\n"), GetLastError());
return -1;
}
else
{
CloseHandle(hThread);
}
}
else
{
HANDLE hTempPipe = hPipe;
hPipe = CreateNewPipe(lpszPipename);
// The client could not connect, so close the pipe.
CloseHandle(hTempPipe);
}
}
return 0;
}
HANDLE CreateNewPipe(LPCWSTR lpszPipename)
{
return CreateNamedPipe(lpszPipename, PIPE_ACCESS_DUPLEX,
PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT, PIPE_UNLIMITED_INSTANCES,
BUFSIZE, BUFSIZE, 0, NULL);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment