所以我有一个服务,它在启动时启动,我有一个应用程序,我已放在启动文件夹中。
因此客户端有时会很晚才连接到命名管道的服务器。
这是我服务中的代码。
hPipe = CreateNamedPipe(TEXT("\\\\.\\pipe\\popupPipe"),
PIPE_ACCESS_DUPLEX | PIPE_TYPE_BYTE | PIPE_READMODE_BYTE, // FILE_FLAG_FIRST_PIPE_INSTANCE is not needed but forces CreateNamedPipe(..) to fail if the pipe already exists...
PIPE_WAIT,
1, 1024 * 16, 1024 * 16,
NMPWAIT_USE_DEFAULT_WAIT,
NULL);
HRESULT
SendMessage(){
if (ConnectNamedPipe(hPipe, NULL) != FALSE) { // wait for someone to connect to the pipe
WriteFile(hPipe, (char *)message->buffer, sizeof(message->buffer), &dwWritten, NULL);
return S_OK;
}
return E_FAIL;
}
这是应用程序
hPipe = CreateFile(TEXT("\\\\.\\pipe\\popupPipe"),
GENERIC_READ | GENERIC_WRITE,
0,
NULL,
OPEN_EXISTING,
0,
NULL);
if (hPipe == INVALID_HANDLE_VALUE)
return -1;
while (hPipe != INVALID_HANDLE_VALUE)
{
DWORD dwRead;
char buffer[100] = { 0 };
while (ReadFile(hPipe, buffer, sizeof(buffer), &dwRead, NULL) != FALSE);
if (dwRead == sizeof(buffer)) {
dwRead = 0;
buffer[100] = '\0';
temp = &buffer[1];
DisplayPopup(hInstance, cmdShow);
}
}
return 0;
但在客户端,应用程序始终返回INVALID_HANDLE_VALUE
在服务中SendMessage
被多次调用,所以即使它第一次失败也应该成功,当客户端连接它时不应该。
答案 0 :(得分:3)
您不会检查管道的创建是否成功。查看Microsoft文档,它可能不会成功,因为您混合了参数:
hPipe = CreateNamedPipe(TEXT("\\\\.\\pipe\\popupPipe"),
PIPE_ACCESS_DUPLEX | PIPE_TYPE_BYTE | PIPE_READMODE_BYTE, // FILE_FLAG_FIRST_PIPE_INSTANCE is not needed but forces CreateNamedPipe(..) to fail if the pipe already exists...
PIPE_WAIT,
1, 1024 * 16, 1024 * 16,
NMPWAIT_USE_DEFAULT_WAIT,
NULL);
应该是:
hPipe = CreateNamedPipe(TEXT("\\\\.\\pipe\\popupPipe"),
PIPE_ACCESS_DUPLEX,
PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT, // FILE_FLAG_FIRST_PIPE_INSTANCE is not needed but forces CreateNamedPipe(..) to fail if the pipe already exists...
1, 1024 * 16, 1024 * 16,
NMPWAIT_USE_DEFAULT_WAIT,
NULL);