Writing and reading from/to a pipe from multiple threads

  • Thread starter Thread starter Stubborn566
  • Start date Start date
S

Stubborn566

Guest
I am trying to create a named pipe(server) from one thread then I wait for the client to connect in separate thread and in client I call CreateFile() and later write to the pipe using that handle, and in the server itself I create another thread to write to the same pipe using same handle I got from CreateNamedPipe(). Whatever the client write I am getting that in the server but whatever I write from the thread in server I am not getting it in the read thread even though the WriteFile() is successful. What is the issue?

Server code:

#include "windows.h"
#include <stdio.h>
#include <string.h>
#include <thread>

//Name given to the pipe
#define g_szPipeName L"\\\\.\\Pipe\\MyNamedPipe1"
//Pipe name format - \\.\pipe\pipename

HANDLE hPipe;
DWORD cbBytes;
#define BUFFER_SIZE 1024 //1k
char szBuffer[BUFFER_SIZE];
#define ACK_MESG_RECV "Message received successfully"
extern "C"
void WriteToPipe(PHANDLE hPipe)
{
//gets_s(szBuffer);
//Reply to client
static int i = 100;
BOOL bResult = false;
while (1)
{
//Send the message to server
bResult = WriteFile(
*hPipe, // handle to pipe
&i,
sizeof(i), // number of bytes to write, include the NULL
&cbBytes, // number of bytes written
NULL); // not overlapped I/O
Sleep(3000);
if ((!bResult) || (sizeof(i) != cbBytes))
{
printf("\nError occurred while writing to the server: %d\n", GetLastError());
//CloseHandle(hPipe);
continue;
}
else
{
printf("\nWriteFile() was successful.\n");
}
i++;
}
CloseHandle(*hPipe);
}

void ReadFromPipe( PHANDLE hPipe)
{
//gets_s(szBuffer);
//Reply to client
int i;
OVERLAPPED olStruct;
ZeroMemory(&olStruct, sizeof(olStruct));

BOOL bSuccess = false;
if(!(olStruct.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL)))
{
printf("\nCreate event failed with error:%d", GetLastError());
}
while (1)
{
BOOL bResult = ReadFile(
*hPipe, // handle to pipe
&i, // buffer to receive data
sizeof(i), // size of buffer
&cbBytes, // number of bytes read
&olStruct); // not overlapped I/O

if (!bResult)
{
DWORD dwLastError = GetLastError();
if (dwLastError != ERROR_IO_PENDING)//shouldn't be successfull, should be ERROR_IO_PENDING
{
printf("ReadFile Success with error %u\n", dwLastError);
}
else
printf("ReadFile %u\n", dwLastError);
}
else
printf("ReadFile succeeded\n");

DWORD dwRet = WaitForSingleObject(olStruct.hEvent, 3000);
DWORD index;
printf("Wait result = 0x%x\n", dwRet);
if (dwRet == 0)
{
{
// This blocks until we receive a value from the interrupt handler.
bSuccess = GetOverlappedResult(
*hPipe,
&olStruct,
&index,
FALSE);

if (bSuccess)
{
printf("ReadFile() was successful.\n");
if (i)
printf("Client sent the following message: %d\n", i);
i = 0;
}
else
{
printf("\nError occurred while reading "
"from the client: %d\n", GetLastError());
continue;
}
}
}
//if ((!bResult) || (0 == cbBytes))
//{
// printf("\nError occurred while reading "
// "from the client: %d", GetLastError());
// //CloseHandle(*hPipe);
//}
//else
//{
// printf("\nReadFile() was successful.");
//}

//i++;
//i = 0;
Sleep(3000);
}
ResetEvent(olStruct.hEvent);
CloseHandle(olStruct.hEvent);
CloseHandle(*hPipe);
}
int main(int argc, char* argv[])
{


hPipe = CreateNamedPipe(
g_szPipeName, // 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
BUFFER_SIZE, // output buffer size
BUFFER_SIZE,
NMPWAIT_USE_DEFAULT_WAIT, // client time-out
NULL); // default security attribute

if (INVALID_HANDLE_VALUE == hPipe)
{
printf("\nError occurred while creating the pipe: %d\n", GetLastError());
return 1; //Error
}
else
{
printf("\nCreateNamedPipe() was successful.\n");
}

printf("\nWaiting for client connection...\n");


//Wait for the client to connect
BOOL bClientConnected = ConnectNamedPipe(hPipe, NULL);


std::thread second(ReadFromPipe, &hPipe);
std::thread first(WriteToPipe, &hPipe);


//if (FALSE == bClientConnected)
//{
// printf("\nError occurred while connecting"
// " to the client: %d", GetLastError());
// CloseHandle(hPipe);
// return 1; //Error
//}
//else
//{
// printf("\nConnectNamedPipe() was successful.");
//}




//We are connected to the client.
//To communicate with the client
//we will use ReadFile()/WriteFile()
//on the pipe handle - hPipe

////Read client message
//BOOL bResult = ReadFile(
// hPipe, // handle to pipe
// szBuffer, // buffer to receive data
// sizeof(szBuffer), // size of buffer
// &cbBytes, // number of bytes read
// NULL); // not overlapped I/O

//if ((!bResult) || (0 == cbBytes))
//{
// printf("\nError occurred while reading "
// "from the client: %d", GetLastError());
// CloseHandle(hPipe);
// return 1; //Error
//}
//else
//{
// printf("\nReadFile() was successful.");
//}

//printf("\nClient sent the following message: %s", szBuffer);

//strcpy_s(szBuffer, ACK_MESG_RECV);


//while (true)
//{
// printf("Enter string:");
// gets_s(szBuffer);
// //Reply to client
// BOOL bResult = WriteFile(
// hPipe, // handle to pipe
// szBuffer, // buffer to write from
// strlen(szBuffer) + 1, // number of bytes to write, include the NULL
// &cbBytes, // number of bytes written
// NULL); // not overlapped I/O

// if ((!bResult) || (strlen(szBuffer) + 1 != cbBytes))
// {
// printf("\nError occurred while writing to the client: %d\n", GetLastError());
// CloseHandle(hPipe);
// return 1; //Error
// }
// else
// {
// printf("\nWriteFile() was successful.\n");
// }
//}
//CloseHandle(hPipe);
return 0; //Success
}

Client code:

#include "windows.h"
#include <stdio.h>


//Name given to the pipe
#define g_szPipeName L"\\\\.\\Pipe\\MyNamedPipe1"
//Pipe name format - \\servername\pipe\pipename
//This pipe is for server on the same computer,
//however, pipes can be used to
//connect to a remote server

#define BUFFER_SIZE 1024 //1k
#define ACK_MESG_RECV "Message received successfully"

int main(int argc, char* argv[])
{
HANDLE hPipe;
DWORD cbBytes;
BOOL bResult;
static int i = 10;

//Connect to the server pipe using CreateFile()
hPipe = CreateFile(
g_szPipeName, // pipe name
GENERIC_READ | // read and write access
GENERIC_WRITE,
FILE_SHARE_WRITE | FILE_SHARE_READ, // no sharing
NULL, // default security attributes
OPEN_EXISTING, // opens existing pipe
0, // default attributes
NULL); // no template file

if (INVALID_HANDLE_VALUE == hPipe)
{
printf("\nError occurred while connecting"
" to the server: %d\n", GetLastError());
//One might want to check whether the server pipe is busy
//This sample will error out if the server pipe is busy
//Read on ERROR_PIPE_BUSY and WaitNamedPipe() for that
return 1; //Error
}
else
{
printf("\nCreateFile() was successful.\n");
}

//We are done connecting to the server pipe,
//we can start communicating with
//the server using ReadFile()/WriteFile()
//on handle - hPipe

//char szBuffer[BUFFER_SIZE];

//printf("\nEnter a message to be sent to the server: ");
//scanf_s("%s", szBuffer, BUFFER_SIZE-1);


while (1)
{
//Send the message to server
bResult = WriteFile(
hPipe, // handle to pipe
&i,
sizeof(i), // number of bytes to write, include the NULL
&cbBytes, // number of bytes written
NULL); // not overlapped I/O
Sleep(3000);
if ((!bResult) || (sizeof(i) != cbBytes))
{
printf("\nError occurred while writing"
" to the server: %d\n", GetLastError());
CloseHandle(hPipe);
return 1; //Error
}
else
{
printf("\nWriteFile() was successful.\n");
}
i++;
Sleep(3000);
}
//while (true)
//{
// printf("Ïn while waiting for read\n");
// //Read server response
// BOOL bResult = ReadFile(
// hPipe, // handle to pipe
// szBuffer, // buffer to receive data
// sizeof(szBuffer), // size of buffer
// &cbBytes,
// NULL);

// if ((!bResult) || (0 == cbBytes))
// {
// printf("\nError occurred while reading from the server: %d\n", GetLastError());
// CloseHandle(hPipe);
// return 1; //Error
// }
// else
// {
// printf("\nReadFile() was successful.\n");
// }

// printf("\nServer sent the following message: %s\n", szBuffer);
//}

CloseHandle(hPipe);
return 0; //Success
}


Please help.

Continue reading...
 
Back
Top