自己写的一个用命名管道用于进程间通信的程序怎么不能达到我预期的结果啊?
客户端:#include <cstdlib>
#include <iostream>
#include <windows.h>
using namespace std;
int main(int argc, char *argv[])
{
HANDLE hPipe;
if(!WaitNamedPipe("\\\\.\\pipe\\ethan",NMPWAIT_WAIT_FOREVER))
{
cout<<"当前没有可用的命名管道实例"<<endl;
system("PAUSE");
return 0;
}
hPipe=CreateFile("\\\\.\\pipe\\ethan",GENERIC_READ|GENERIC_WRITE
,0,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
if(INVALID_HANDLE_VALUE==hPipe){
cout<<"打开命名管道失败"<<endl;
hPipe=NULL;
system("PAUSE");
return 0;
}
char buf[]="我帅不帅?";
DWORD dwWrite;
if(!WriteFile(hPipe,buf,strlen(buf)+1,&dwWrite,NULL)){
cout<<"写入数据失败"<<endl;
system("pause");
return 0;
}
system("PAUSE");
return EXIT_SUCCESS;
}
服务端:
#include <cstdlib>
#include <iostream>
#include <windows.h>
#include <string>
using namespace std;
DWORD WINAPI Wait(
LPVOID lpParameter // thread data
);
HANDLE hPipe;
int main(int argc, char *argv[])
{
SECURITY_ATTRIBUTES sa;
sa.bInheritHandle=true;
CreateNamedPipe("\\\\.\\pipe\\ethan",PIPE_ACCESS_DUPLEX|FILE_FLAG_OVERLAPPED,
0,1,1024,1024,0,
NULL);
if(hPipe==INVALID_HANDLE_VALUE){
cout<<"创建命名管道失败"<<endl;
hPipe=NULL;
system("PAUSE");
return 0;
}
HANDLE hThread;
hThread=CreateThread(NULL,0,Wait,NULL,0,NULL);
while(true){}
system("PAUSE");
return EXIT_SUCCESS;
}
DWORD WINAPI Wait(
LPVOID lpParameter // thread data
){
HANDLE hEvent;
hEvent=CreateEvent(NULL,true,false,NULL);
if(!hEvent){
cout<<"创建事件对象失败"<<endl;
CloseHandle(hEvent);
hEvent=NULL;
system("PAUSE");
return 0;
}
OVERLAPPED ol;
ol.hEvent=hEvent;
if(!ConnectNamedPipe(hPipe,&ol)){
if(ERROR_PIPE_CONNECTED!=GetLastError()){
cout<<"等待客户端失败"<<endl;
CloseHandle(hPipe);
CloseHandle(hEvent);
hPipe=NULL;
}
}
if(!WAIT_FAILED==WaitForSingleObject(hEvent,INFINITE)){
cout<<"等待对象失败"<<endl;
CloseHandle(hPipe);
CloseHandle(hEvent);
hPipe=NULL;
}
char buf[100];
DWORD dwRead;
while(true){
if(!ReadFile(hPipe,buf,100,&dwRead,NULL)){
cout<<"读取数据失败"<<endl;
continue;
}
cout<<buf;
}
}
请问如何改才能让服务端读到数据并显示出来?
[[it] 本帖最后由 george_vcool 于 2008-4-1 22:26 编辑 [/it]]