Named Pipes are useful in Inter Process communication. Pipes will always have two ends. One on the Server (usually to listen and reply) and the client which connects and sends messages. So Pipes can be used in communicating among two programs very conveniently.
This article includes a sample for Named Pipe client. This program is based on the CreateNamedPipe Server article, which creates pipe as \.pipeSamplePipe.
A client pipe is created by using CreateFile function with the pipe name. The pipe name must be the same as the server pipe. Otherwise this function will return an error. The whole set of client side operations are like file handling only.
After successfully creating the pipe client, a call to the WriteFile function will transfer the data to the Named Pipe server.
Named Pipe Client – Sample:
#include <windows.h> #include <stdio.h> #define BUFSIZE 1024 #define PIPE_TIMEOUT 5000 int main() { HANDLE hFile; BOOL flg; DWORD dwWrite; char szPipeUpdate[200]; hFile = CreateFile("\\.\pipe\SamplePipe", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); strcpy(szPipeUpdate,"Data from Named Pipe client for createnamedpipe"); if(hFile == INVALID_HANDLE_VALUE) { printf("CreateFile failed for Named Pipe clientn" ); } else { flg = WriteFile(hFile, szPipeUpdate, strlen(szPipeUpdate), &dwWrite, NULL); if (FALSE == flg) { printf("WriteFile failed for Named Pipe clientn"); } else { printf("WriteFile succeeded for Named Pipe clientn"); } CloseHandle(hFile); } }
The above sample connects to the named pipe server and sends the data as in the variable szPipeUpdate.