这种匿名管道,和读写文件类似。最好是一个进程读,一个进程写,适合单向通信,不适于双向通信,双向通信容易导致的问题是有可能,读到自己进程刚才写的内容。
纯手工代码,没有一丝拷贝
父进程代码:
// PipeServer.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <Windows.h> #include <iostream> using namespace std; #define BUFF_SIZE 1024 void Test() { SECURITY_ATTRIBUTES sec_handle = {0}; sec_handle.bInheritHandle = TRUE; sec_handle.lpSecurityDescriptor = NULL; sec_handle.nLength = sizeof(sec_handle); HANDLE hReadPipe = INVALID_HANDLE_VALUE; HANDLE hWritePipe = INVALID_HANDLE_VALUE; BOOL bCrtPipeOk = CreatePipe(&hReadPipe,&hWritePipe,&sec_handle,BUFF_SIZE); if(!bCrtPipeOk) return ; STARTUPINFO siStartInfo; ZeroMemory( &siStartInfo, sizeof(STARTUPINFO) ); siStartInfo.cb = sizeof(STARTUPINFO); PROCESS_INFORMATION piProcInfo; ZeroMemory( &piProcInfo, sizeof(PROCESS_INFORMATION) ); TCHAR szCommandLine[256] = {0}; _stprintf_s(szCommandLine,_T("-hReadPipe %d -hWritePipe %d"),hReadPipe,hWritePipe); if(!::CreateProcess( _T("PipeClient.exe"), szCommandLine, NULL, NULL, TRUE, 0 | CREATE_NEW_CONSOLE, NULL, NULL, &siStartInfo, &piProcInfo)) { int nError = ::GetLastError(); cout<<"创建进程失败:"<<nError<<endl; return; } while(1) { char szReadBuf[BUFF_SIZE] = {0}; cout<<"Server Reading....."<<endl; DWORD dwReaded = 0; BOOL bRead = ::ReadFile(hReadPipe,szReadBuf,BUFF_SIZE,&dwReaded,NULL); if(!bRead) cout<<"ReadFile Error: "<<::GetLastError()<<endl; else wcout<<L"Readed content:"<<szReadBuf<<endl; cout<<"Server Writeing ... "<<endl; char szWrite[] = {"I'm Server"}; DWORD dwWritten = 0; if(!::WriteFile(hWritePipe,szWrite, sizeof(szWrite), &dwWritten, NULL)) { cout<<"Server Write Error:"<<::GetLastError()<<endl; } else cout<<"ServerWrite Ok!!!"<<endl; Sleep(1000); } } int _tmain(int argc, _TCHAR* argv[]) { Test(); system("pause"); return 0; }
子进程 代码
// PipeClient.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <iostream> #include <Windows.h> using namespace std; void Test(HANDLE hRead,HANDLE hWrite) { char szWrite[] = ("I'm Client!!"); DWORD dwWritten = 0; cout<<"client now Write...."<<endl; if(!::WriteFile(hWrite, szWrite, sizeof(szWrite), &dwWritten, NULL)) { int nError = ::GetLastError(); cout<<"写文件出错:"<<nError<<endl; return ; } cout<<"client write finished"<<endl; char szRead[256] = {0}; DWORD dwReaded = 0; cout<<"client start read......"<<endl; if(!ReadFile(hRead,szRead,sizeof(szRead),&dwReaded,NULL)) { int nError = ::GetLastError(); cout<<"读文件出错:"<<nError<<endl; return ; } else cout<<"client read:"<<szRead<<endl; } int _tmain(int argc, _TCHAR* argv[]) { if(argc <= 1) return 0; HANDLE hReadPipe = (HANDLE) _tstoi(argv[1]); HANDLE hWritePipe = (HANDLE) _tstoi(argv[3]); //DebugBreak(); Test(hReadPipe,hWritePipe); system("pause"); return 0; }