我将以下代码作为另一个向客户端发送消息的模块的一部分。这是针对IPC的。两个dll由exe加载,这两个需要通信
在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-1的其他地方,我有以下服务器
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。
非常感谢任何指导。
答案 0 :(得分:0)
您正在调用错误的方法。管道应该预先存在,因此您应该调用OpenFile()
,而不是CreateFile()
。
答案 1 :(得分:0)
啊,我找到了挂起的答案,我必须做一个PeekNamedPipe(pipe2, NULL, 0, NULL, &bytesAvailable, NULL);
,然后在我做ReadFile()
之前检查bytesAvailable是否大于零