I have created a small server program that encrypts text using a named pipe:
#define UNICODE
#define WIN32_WINNT 0x0500
#include <stdio.h>
#include <windows.h>
#include <signal.h>
HANDLE hPipe;
DWORD WINAPI ServerProc(LPVOID lpVoid)
{
hPipe = CreateNamedPipe(L"\\\\.\\pipe\\testpipe", PIPE_ACCESS_DUPLEX, PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |PIPE_WAIT, 1, 256, 256, 0, NULL);
if(!hPipe)
return wprintf(L"ERROR : Cannot create pipe.\n");
while(ConnectNamedPipe(hPipe, NULL))
{
WCHAR szText[80] = {0};
DWORD dwSize;
INT i;
ReadFile(hPipe, szText, 158, &dwSize, NULL);
for(i = 0; i < dwSize; i++)
szText[i] ^= '#';
WriteFile(hPipe, szText, 158, &dwSize, NULL);
FlushFileBuffers(hPipe);
DisconnectNamedPipe(hPipe);
}
CloseHandle(hPipe);
return 0;
}
void SignalHandler(int signal)
{
DisconnectNamedPipe(hPipe);
CloseHandle(hPipe);
printf("Application closing...\n");
exit(0);
}
int wmain(void)
{
HANDLE hThread;
signal(SIGINT, SignalHandler);
hThread = CreateThread(NULL, 0, ServerProc, NULL, 0, NULL);
WaitForSingleObject(hThread, INFINITE);
CloseHandle(hThread);
}
In this code I have created a hPipe
handle as global because my program thread and the signal handler both need the handle.
Is this a correct way to handle signals?