I need my client to first check if server is reading data from pipe, if yes then wait till server is done else write data into pipe. If I don't use sleep command in my sample client program then Server doesn't read message properly.I found the reason of this issue from the documentation it says:
This buffer must remain valid for the duration of the read operation. The caller must not use this buffer until the read operation is completed.
But it doesn't specify how to block client until the read operation is complete.
Server Code:
#include<stdio.h>
#include<windows.h>
#include<iostream>
using namespace std;
int main(void)
{
HANDLE hPipe;
char buffer[1024];
DWORD dwRead;
hPipe = CreateNamedPipe(TEXT("\\\\.\\pipe\\Pipe"),
PIPE_ACCESS_INBOUND | FILE_FLAG_FIRST_PIPE_INSTANCE,
PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT,
1,
1024 * 16,
1024 * 16,
NMPWAIT_USE_DEFAULT_WAIT,
NULL);
while (hPipe != INVALID_HANDLE_VALUE)
{
if (ConnectNamedPipe(hPipe, NULL) != FALSE) // wait for someone to connect to the pipe
{
while (ReadFile(hPipe, buffer, sizeof(buffer) - 1, &dwRead, NULL) != FALSE)
{
/* add terminating zero */
buffer[dwRead] = '\0';
/* do something with data in buffer */
printf("%s", buffer);
}
}
DisconnectNamedPipe(hPipe);
}
return 0;
}
Client Code:
#include<stdio.h>
#include<windows.h>
#include<iostream>
#include<stdlib.h>
using namespace std;
void fun()
{
HANDLE hPipe;
DWORD dwWritten;
hPipe = CreateFile(TEXT("\\\\.\\pipe\\Pipe"),
GENERIC_WRITE,
0,
NULL,
OPEN_EXISTING,
0,
NULL);
if (hPipe != INVALID_HANDLE_VALUE)
{
WriteFile(hPipe,
"Hello Pipe",
11, // = length of string + terminating '\0' !!!
&dwWritten,
NULL);
CloseHandle(hPipe);
}
}
int main(void)
{
int a = 5;
cout<<a;
for(int i = 0; i<a; i++)
{
fun();
Sleep(2000);
}
return (0);
}
This is just a sample program, actually my client is a very big application it has many functions and I don't want to make any major changes in it. Whenever a particular function gets triggered it should pass data to server. The type of data is a structure. After receiving data in server I want to write that data into text file (After converting it into json format).
So how can I make my client to check if the server is done reading data from pipe before writing data into pipe? Client should not wait forever for the server as it will affect my client application. It should wait for a specified time interval. Also to pass structure which pipe mode should I use BYTE MODE or MESSAGE MODE?