Created
April 12, 2017 07:55
-
-
Save lestera/fd808ac743d2d25b006101f6e24b375d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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. | |
for (;;) | |
{ | |
_tprintf( TEXT("\nPipe Server: Main thread awaiting client connection on %s\n"), lpszPipename); | |
hPipe = CreateNamedPipe( | |
lpszPipename, // pipe name | |
PIPE_ACCESS_DUPLEX, // read/write access | |
PIPE_TYPE_MESSAGE | // message type pipe | |
PIPE_READMODE_MESSAGE | // message-read mode | |
PIPE_WAIT, // blocking mode | |
PIPE_UNLIMITED_INSTANCES, // max. instances | |
BUFSIZE, // output buffer size | |
BUFSIZE, // input buffer size | |
0, // client time-out | |
NULL); // default security attribute | |
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"); | |
// 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) | |
{ | |
_tprintf(TEXT("CreateThread failed, GLE=%d.\n"), GetLastError()); | |
return -1; | |
} | |
else CloseHandle(hThread); | |
} | |
else | |
// The client could not connect, so close the pipe. | |
CloseHandle(hPipe); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment