Question : Use of Pipes?

I have a function in my MFC program:

void myPipe()
{
BYTE sBuf[100]="Send #1";
BYTE rBuf[100];
HANDLE hPipeInst, hPipe;
     
hPipeInst=CreateNamedPipe("//./pipe/aPipe", PIPE_ACCESS_DUPLEX, PIPE_TYPE_BYTE, 10, 100, 100, 10000, NULL);

int errorCode= GetLastError(); //ok here

hPipe=CreateFile("//./pipe/aPipe", GENERIC_READ|GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);

errorCode= GetLastError(); //ok here

WriteFile(hPipe, sBuf, 8, &len, NULL);

ReadFile(hPipe, rBuf, 8, &len, NULL); //wrong
}

The last call "ReadFile()" never got returned(as I debug it). What is wrong with the program?

Answer : Use of Pipes?


There's lots of stuff wrong with your code, yingchunli.

1) You're writing to the client side of the pipe, not the source side. What's written to a pipe isn't echoed back into it by itself.

2) You never define the varaible "len".

3) You use forward slashes instead of backslashes.

4) You never close the pipes.


Here's a module that compiles and executes correctly.


-- begin pipe.cpp --

#include
#include

int main()
{
   BYTE sBuf[100]="Send #1";
   BYTE rBuf[100];
   HANDLE hPipeInst, hPipe;
   DWORD len;
   
   hPipeInst=CreateNamedPipe("\\\\.\\pipe\\aPipe", PIPE_ACCESS_DUPLEX, PIPE_TYPE_BYTE, 10, 100, 100, 10000,
NULL);

   int errorCode= GetLastError(); //ok here

   hPipe=CreateFile("\\\\.\\pipe\\aPipe", GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

   errorCode= GetLastError(); //ok here

   WriteFile(hPipeInst, sBuf, 8, &len, NULL);
   ReadFile(hPipe, rBuf, 8, &len, NULL); //wrong

   rBuf[len] = 0;
   printf("Read \"%s\"\n", rBuf);

   CloseHandle(hPipe);
   CloseHandle(hPipeInst);

   return 0;
}

-- end pipe.cpp ---

.B ekiM

Random Solutions  
 
programming4us programming4us