我将以下代码作为向客户端发送消息的另一个模块的一部分。这是针对IPC的。exe加载了两个dll,这两个需要通信
在DLL-1中,我有下面一行代码作为服务器名为pipe。
pipe = CreateNamedPipe("\\\\.\\pipe\\S2D8",PIPE_ACCESS_OUTBOUND | FILE_FLAG_OVERLAPPED /**1-way, send only with overlapped IO*/,
PIPE_TYPE_MESSAGE,1,0,0, 0, NULL);
if( INVALID_HANDLE_VALUE != pipe )
{
log("Created Named Pipe as Serverl\n");
}
else
{
log("Cannot create Named Pipe as Server\n");
}在DLL中的其他地方,我为服务器提供了以下内容
bool result = ConnectNamedPipe(pipe, NULL);
if (!result)
{
CloseHandle(pipe); // close the pipe
}
else
{
DWORD numWritten;
WriteFile(pipe,KeyBoardBuffer,strlen(KeyBoardBuffer) * sizeof(char),&numWritten,0);
log("Bytes writtern to pipe:%d\n",numWritten);
}当我查看日志时,我可以看到那个命名管道。到目前为止还不错。
在DLL-2中,我将以下内容作为客户端部分
log("Connecting to named pipe at client\n");
if(pipe2 == NULL || pipe2 == INVALID_HANDLE_VALUE)
{
pipe2 = CreateFile("\\\\.\\pipe\\S2D8", GENERIC_READ ,
FILE_SHARE_READ | FILE_SHARE_WRITE,NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL,NULL);
if (pipe2 == INVALID_HANDLE_VALUE)
{
log("Cannot connect to named pipe at client%x\n", GetLastError());
CloseHandle(pipe2);
}
else
{
log("Connected to named pipe at client! Going to read!!!\n");
char buffer[256] = {'\0'};
DWORD numBytesRead = 0;
BOOL result = ReadFile(
pipe2,
buffer, // the data from the pipe will be put here
sizeof(buffer) * sizeof(char), // number of bytes allocated
&numBytesRead, // this will store number of bytes actually read
NULL // not using overlapped IO
);
if (result)
{
kbBuffer[numBytesRead / sizeof(char)] = '\0'; // null terminate the string
log( "Number of bytes read: %d\n",numBytesRead);
log(kbBuffer );
}
else
{
log("Failed to read data from the pipe.\n");
}
}
}在我的日志中,我可以看到行“正在连接到客户端的命名管道”,然后是“连接到客户端的命名管道!正在读取!”,之后日志中没有任何内容,所有内容似乎都卡住了。
管道的命名约定是否正确?或者,是否有我必须定义的安全设置?
我正在使用VS2010,Win7 x64。
任何指导都是非常感谢的。
发布于 2015-02-19 15:47:22
您调用了错误的方法。管道应该是预先存在的,所以您应该调用OpenFile(),而不是CreateFile()。
发布于 2015-02-19 16:26:03
啊,我找到了挂起的答案,我必须做一个PeekNamedPipe(pipe2, NULL, 0, NULL, &bytesAvailable, NULL);,然后在做ReadFile()之前检查bytesAvailable是否大于零
https://stackoverflow.com/questions/28600680
复制相似问题