【发布时间】:2017-09-30 03:50:36
【问题描述】:
我正在尝试让 C++ 应用程序让 C# 应用程序知道特定操作何时发生。我试图做到这一点的方式是通过命名管道。
我已经在 C++ 应用程序上设置了一个命名管道服务器,它似乎正在工作(命名管道被创建 - 它出现在由PipeList 检索的列表中)和一个命名管道客户端在 C# 应用程序上,失败的地方:C# 客户端代码的第一行给出“管道句柄尚未设置。您的 PipeStream 实现是否调用了 InitializeHandle?”错误,第 2 行抛出“访问路径被拒绝”异常。
我哪里错了?
C++ 服务器代码
CString namedPipeName = "\\\\.\\pipe\\TitleChangePipe";
HANDLE pipe = CreateNamedPipe(namedPipeName, PIPE_ACCESS_INBOUND , PIPE_WAIT, 1, 1024, 1024, 120 * 1000, NULL);
if (pipe == INVALID_HANDLE_VALUE) {
MessageBox(NULL, "Pipe Could Not be Established.", "Error: TCM", MB_ICONERROR);
return -1;
}
char line[512]; DWORD numRead;
while (true)//just keep doing this
{
numRead = 1;
while ((numRead < 10 || numRead > 511) && numRead > 0)
{
if (!ReadFile(pipe, line, 512, &numRead, NULL) || numRead < 1) {//Blocking call
CloseHandle(pipe); //If something went wrong, reset pipe
pipe = CreateNamedPipe(namedPipeName, PIPE_ACCESS_INBOUND , PIPE_WAIT, 1, 1024, 1024, 120 * 1000, NULL);
ConnectNamedPipe(pipe, NULL);
if (pipe == INVALID_HANDLE_VALUE) {
MessageBox(NULL, "Pipe Could Not be Established.", "Error: TCM", MB_ICONERROR);
return -1; }
numRead = 1;
}
}
line[numRead] = '\0'; //Terminate String
}
CloseHandle(pipe);
C# 客户端代码
var client = new NamedPipeClientStream(".", "TitleChangePipe", PipeDirection.InOut);
client.Connect();
var reader = new StreamReader(client);
var writer = new StreamWriter(client);
while (true)
{
var input = Console.ReadLine();
if (String.IsNullOrEmpty(input))
break;
writer.WriteLine(input);
writer.Flush();
Console.WriteLine(reader.ReadLine());
}
【问题讨论】:
标签: c# c++ windows ipc named-pipes