命名pipe道服务和应用程序之间的通信

所以我有一个服务,在启动时开始,我有一个应用程序,我已经放在启动文件夹。

所以客户端有时会连接到命名pipe道的服务器。

这是我的代码在我的服务。

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 ,所以即使第一次失败,它应该成功,当客户端连接不应该它。

您不检查管道的创建是否成功。 看着微软的文档,它可能不会成功,因为你混合的参数:

 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);