C++ 管道
服务端:
// PipeServer.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <windows.h> using namespace std; int _tmain(int argc, _TCHAR* argv[]) { HANDLE hPipe = CreateNamedPipeW(L"\\\\.\\pipe\\PipeTest", PIPE_ACCESS_DUPLEX, PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT, PIPE_UNLIMITED_INSTANCES, 4096, 4096, 0, NULL); //PIPE_ACCESS_DUPLEX 表示可读可写 if (hPipe == INVALID_HANDLE_VALUE) { printf("create pipe fail\n"); } if (ConnectNamedPipe(hPipe, NULL) || (GetLastError() == ERROR_PIPE_CONNECTED)) { DWORD cbBytesRead; char chRequest[4096]; bool fSuccess = ReadFile(hPipe, chRequest, 4096, &cbBytesRead, NULL); chRequest[cbBytesRead] = '\0'; printf("%s\n", chRequest); if (!fSuccess || cbBytesRead == 0) { } char str[] = {"123123"}; WriteFile(hPipe, str, strlen(str), &cbBytesRead, NULL); Sleep(2000); DisconnectNamedPipe(hPipe); } else { CloseHandle(hPipe); printf("close"); } CloseHandle(hPipe); return 0; }
客户端端:
// PipeClient.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <windows.h> int _tmain(int argc, _TCHAR* argv[]) { HANDLE m_hPipeToMain = CreateFile(L"\\\\.\\pipe\\PipeTest", GENERIC_WRITE | GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL); if (m_hPipeToMain != 0 || m_hPipeToMain == INVALID_HANDLE_VALUE) { DWORD dwWrite; char szPipeUpdate[200] = "send message form client"; WriteFile(m_hPipeToMain, szPipeUpdate, strlen(szPipeUpdate), &dwWrite, NULL); printf("send pipe success\n"); ZeroMemory(szPipeUpdate, 200); ReadFile(m_hPipeToMain, szPipeUpdate, 200, &dwWrite, NULL); Sleep(2000); printf("%s\n", szPipeUpdate); CloseHandle(m_hPipeToMain); } else{ printf("ERROR\n"); } return 0; }
版权声明:本文为博主原创文章,未经博主允许不得转载。