C and C++ processes communicate instances of of named pipes

  • 2020-05-27 06:33:24
  • OfStack

Server code:


// pipe_server.cpp :  Define the entry point for the console application. 
//
 
#include "stdafx.h"
#include <stdio.h>
#include <windows.h>
#include <ctime>
 
int main(int argc, _TCHAR* argv[])
{
   srand(time(NULL));
 
  char buf[256] = "";
   DWORD rlen = 0;
   HANDLE hPipe = CreateNamedPipe(
     TEXT("\\\\.\\Pipe\\mypipe"),            // Channel name 
     PIPE_ACCESS_DUPLEX,                  // The pipe type 
     PIPE_TYPE_MESSAGE|PIPE_READMODE_MESSAGE|PIPE_WAIT,  // Pipe parameters 
     PIPE_UNLIMITED_INSTANCES,              // The maximum number of instances a pipe can create 
     0,                          // Output buffer length  0 Said the default 
     0,                          // Input buffer length  0 Said the default 
     NMPWAIT_WAIT_FOREVER,                // timeout 
     NULL);                        // The specified 1 a SECURITY_ATTRIBUTES structure , Or pass zero 
 
  if (INVALID_HANDLE_VALUE == hPipe)
   {
     printf("Create Pipe Error(%d)\n",GetLastError());
   }
   else
   {
     printf("Waiting For Client Connection...\n");
 
    if(!ConnectNamedPipe(hPipe, NULL))  // Block waiting for client connection. 
     {
       printf("Connection failed!\n");
     }
     else
     {
       printf("Connection Success!\n");
     }
 
    while (true)
     {
       if(!ReadFile(hPipe,buf,256,&rlen,NULL)) // Accept what the client sends 
       {      
         printf("Read Data From Pipe Failed!\n");
         break;
       }
       else
       {
         printf("From Client: data = %s, size = %d\n", buf, rlen);
         
         char wbuf[256] = "";
         sprintf(wbuf, "%s%d", wbuf, rand()%1000);
         DWORD wlen = 0;
         WriteFile(hPipe, wbuf, sizeof(wbuf), &wlen, 0);  // Send content to the client 
         printf("To Client: data = %s, size = %d\n", wbuf, wlen);
         Sleep(1000);
       }
     }
     FlushFileBuffers(hPipe);
     DisconnectNamedPipe(hPipe);
     CloseHandle(hPipe);// Close the pipeline 
   }
 
  system("pause");
   return 0;
}

Client code:


// pipe_client.cpp :  Define the entry point for the console application. 
//
 
#include "stdafx.h"
#include <stdio.h>
#include <windows.h>
#include <ctime>
 
int main(int argc, _TCHAR* argv[])
{
   srand(time(NULL));
 
  DWORD wlen = 0;
   Sleep(1000);// Waiting for the pipe The creation of successful! 
 
  BOOL bRet = WaitNamedPipe(TEXT("\\\\.\\Pipe\\mypipe"), NMPWAIT_WAIT_FOREVER);
 
  if (!bRet)
   {
     printf("connect the namedPipe failed!\n");
     return 0;
   }
 
  HANDLE hPipe = CreateFile(      // Pipeline belongs to 1 A special kind of document 
     TEXT("\\\\.\\Pipe\\mypipe"),  // File name created 
     GENERIC_READ | GENERIC_WRITE,  // File pattern 
     0,                // Whether or not to share 
     NULL,              // Point to the 1 a SECURITY_ATTRIBUTES Pointer to structure 
     OPEN_EXISTING,          // Create a parameter 
     FILE_ATTRIBUTE_NORMAL,      // File attributes ( hidden , read-only )NORMAL Is the default property 
     NULL);              // Handle to the template creation file 
 
  if (INVALID_HANDLE_VALUE == hPipe)
   {
     printf("open the exit pipe failed!\n");
   }
   else
   {
     while(true)
     {
       char buf[256] = "";
       sprintf(buf,"%s%d",buf,rand()%1000);
       if(WriteFile(hPipe,buf,sizeof(buf),&wlen,0)==FALSE)  // Send content to the server 
       {
         printf("write to pipe failed!\n");
         break;
       }
       else
       {
         printf("To Server: data = %s, size = %d\n", buf, wlen);
         char rbuf[256] = "";
         DWORD rlen = 0;
         ReadFile(hPipe, rbuf, sizeof(rbuf), &rlen, 0);  // Accept the content sent by the service 
         printf("From Server: data = %s, size = %d\n", rbuf, rlen);
       }
       Sleep(1000);
     }
     CloseHandle(hPipe);// Close the pipeline 
   }
 
  system("pause");
   return 0;
}

Related articles: