Windows命名管道-客户端示例代码
#include
#include
#include
#include
#include
#pragma comment (lib, "Ws2_32.lib")
#define PIPE_NAME "\\\\.\\pipe\\mypipe"
int main( int argc, char *argv[] );
static HANDLE cmdrcpt_connect( void );
static int cmdrcpt_communication ( HANDLE conFd);
int main( int argc, char *argv[] )
{
HANDLE ret;
if( (ret = cmdrcpt_connect()) == NULL){
exit(0);
return 0;
}
if( cmdrcpt_communication( ret ) == -1 ){
exit(0);
return 0;
}
exit(0);
return 0;
}
static
HANDLE cmdrcpt_connect( void )
{
HANDLE PipeHandle;
if( WaitNamedPipe(PIPE_NAME, NMPWAIT_WAIT_FOREVER) == 0 )
{
printf("WaitNamedPipe failed with error %d\n", GetLastError());
return NULL;
}
//Create the named pipe file handle
if( (PipeHandle = CreateFile(PIPE_NAME,
GENERIC_READ | GENERIC_WRITE, 0,
(LPSECURITY_ATTRIBUTES)NULL, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
(HANDLE)NULL)) == INVALID_HANDLE_VALUE )
{
printf("CreateFile failed with error %d\n", GetLastError());
return NULL;
}
return PipeHandle;
}
static
int cmdrcpt_communication ( HANDLE conFd )
{
unsigned long BytesWritten;
unsigned long BytesRead;
char buffer[256]={0};
if( WriteFile(conFd, "This is a test", 14, &BytesWritten, NULL) == 0 )
{
printf("WriteFile failed with error %d\n", GetLastError());
CloseHandle(conFd);
return 0;
}
printf("Wrote %d bytes\n", BytesWritten);
#if 0
if( ReadFile(conFd, buffer, sizeof(buffer), &BytesRead, NULL) <=0 )
{
printf("ReadFile failed with error %d", GetLastError());
CloseHandle(conFd);
return 0;
}
printf("read %d bytes [%s]\n", BytesRead, buffer);
#endif
Sleep(2000);
CloseHandle(conFd);
return 1;
}