C++匿名管道
实现效果:
程序通过创建子进程方式创建一个cmd控制台程序,通过匿名管道进行命令的输入和读取。
用到的结构有:
typedef struct _STARTUPINFO { DWORD cb; LPTSTR lpReserved; LPTSTR lpDesktop; LPTSTR lpTitle; DWORD dwX; DWORD dwY; DWORD dwXSize; DWORD dwYSize; DWORD dwXCountChars; DWORD dwYCountChars; DWORD dwFillAttribute; DWORD dwFlags; WORD wShowWindow; WORD cbReserved2; LPBYTE lpReserved2; HANDLE hStdInput; HANDLE hStdOutput; HANDLE hStdError; } STARTUPINFO, *LPSTARTUPINFO;
typedef struct _PROCESS_INFORMATION { HANDLE hProcess; HANDLE hThread; DWORD dwProcessId; DWORD dwThreadId; } PROCESS_INFORMATION;
typedef struct _SECURITY_ATTRIBUTES { DWORD nLength; / /结构体的大小,可用SIZEOF取得 LPVOID lpSecurityDescriptor; / /安全描述符 BOOL bInheritHandle ;/ /安全描述的对象能否被新创建的进程继承 } SECURITY_ATTRIBUTES,* PSECURITY_ATTRIBUTES;
//头部文件文件 #include <Windows.h> #include <iostream.h> #include <stdio.h> SECURITY_ATTRIBUTES saa,sab; PROCESS_INFORMATION pi; STARTUPINFO sui; HANDLE mReadPipe,mWritePipe,mReadFile,mWriteFile; HANDLE mThread; DWORD dwRead; void closehandle() { CloseHandle(mReadPipe); CloseHandle(mWritePipe); CloseHandle(mReadFile); CloseHandle(mWriteFile); mReadPipe=NULL; mWritePipe=NULL; mReadFile=NULL; mWriteFile=NULL; mThread=NULL; } DWORD WINAPI PipeProc( LPVOID lpParameter // thread data ) { HANDLE hRead = (HANDLE)lpParameter; char buf[1024]; memset(buf,0,1024); DWORD dwRead; while(1) { PeekNamedPipe(hRead,buf,1024,&dwRead,NULL,NULL); if(dwRead != 0) { ReadFile(hRead,buf,1024,&dwRead,NULL); cout<<buf<<endl; memset(buf,0,sizeof(buf)); } } return 0; }; void main() { //初始化SECURITY_ATTRIBUTES结构 saa.bInheritHandle = TRUE; saa.lpSecurityDescriptor=NULL; saa.nLength = sizeof(SECURITY_ATTRIBUTES); sab.bInheritHandle = TRUE; sab.lpSecurityDescriptor=NULL; sab.nLength = sizeof(SECURITY_ATTRIBUTES); //创建匿名管道 if(!CreatePipe(&mReadPipe,&mWriteFile,&saa,0)) { cout<<"创建匿名管道失败"<<endl; return; } if(!CreatePipe(&mReadFile,&mWritePipe,&sab,0)) { cout<<"创建匿名管道失败"<<endl; return; } ZeroMemory(&sui,sizeof(STARTUPINFO)); //结构初始化为0 GetStartupInfo(&sui); //获取调用进程信息 sui.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES; sui.wShowWindow = SW_HIDE; sui.hStdInput = mReadPipe; sui.hStdOutput = mWritePipe; sui.hStdError = mWritePipe; if(!CreateProcess(NULL,"cmd.exe",NULL,NULL,TRUE,0,NULL,NULL,&sui,&pi)) { cout<<"创建子进程失败"<<endl; closehandle(); return; } mThread = CreateThread(NULL,0,PipeProc,(LPVOID)mReadFile,0,NULL); if(NULL==mThread) { cout<<"创建线程失败!"<<endl; closehandle(); return; } CloseHandle(mThread); Sleep(100); while(1) { char buf[256]; memset(buf,0,256); cout<<"Command:"<<flush; gets(buf); if(strcmp(buf,"exit")!=0) { buf[strlen(buf)]='\n'; WriteFile(mWriteFile,buf,strlen(buf),&dwRead,NULL); Sleep(100); } else break; } closehandle(); cout<<"程序运行结束!"<<endl; system("pause"); exit(0); }
欢迎 C++/Python 的朋友一起交流学习, My QQ Number: 2303186535
-- 来自m星人的问候