Visual c++ 服务中使用的Windows命名管道不工作

Visual c++ 服务中使用的Windows命名管道不工作,visual-c++,service,named-pipes,Visual C++,Service,Named Pipes,我正在使用windows命名的管道示例。当我运行示例程序来创建管道,编写一些东西并在客户端程序中接收时,一切都很好。当我将客户端代码移动到运行在windows服务中的dll中时,它不会接收发送的字节 服务器的代码如下所示: ThreadParams * params = reinterpret_cast<ThreadParams*>(args); CString * connectionString = params->connectString; HANDLE hPipe;

我正在使用windows命名的管道示例。当我运行示例程序来创建管道,编写一些东西并在客户端程序中接收时,一切都很好。当我将客户端代码移动到运行在windows服务中的dll中时,它不会接收发送的字节

服务器的代码如下所示:

ThreadParams * params = reinterpret_cast<ThreadParams*>(args);
CString * connectionString = params->connectString;

HANDLE hPipe;
DWORD dwBytesRead;
TCHAR buf[1024];
int len;

hPipe = CreateNamedPipe(PIPE_NAME,  // Name
                        PIPE_ACCESS_OUTBOUND | WRITE_OWNER, // OpenMode
                        PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT, // PipeMode
                        2, // MaxInstances
                        1024, // OutBufferSize
                        1024, // InBuffersize
                        2000, // TimeOut
                        NULL); // Security
if (hPipe == INVALID_HANDLE_VALUE)
{
    Globals::WriteLog("Could not create the pipe",1);
    exit(1);
}

Globals::WriteLog("connect...",1);
ConnectNamedPipe(hPipe, NULL);
Globals::WriteLog("...connected",1);

swprintf(buf, connectionString->GetBuffer());
len = wcslen(buf);

if (!WriteFile(hPipe, buf, len*sizeof(TCHAR), &dwBytesRead, NULL))
    Globals::WriteLog("WriteFile failed",1);
else
    wprintf(L"written %d bytes\n",dwBytesRead);

DisconnectNamedPipe(hPipe);

CloseHandle(hPipe);
服务器的代码在一个线程中运行,如果这改变了什么(我已经在示例程序中用这个线程版本测试了它,并且没有问题)

为什么它不起作用


提前谢谢

好的,看来我已经明白了。似乎我没有正确理解文档

在服务器端,WriteFile函数在读取字符串之前不会阻塞。我的程序只是写数据,然后关闭句柄管道。客户端未捕获消息,并抛出错误,指出管道的另一端没有进程

我也从客户机中删除了(;;)循环

为了等待客户端上的读取操作完成,我添加了

FlushFileBuffers(hPipe);
成功写入操作后

希望能帮助别人

FlushFileBuffers(hPipe);