VC使用管道重定向进程输入输出

来源:互联网 发布:python中get函数 编辑:程序博客网 时间:2024/06/05 13:25

创建管道

std::string sLog;HANDLE hRead1, hWrite1, hRead2, hWrite2;SECURITY_ATTRIBUTES sat;sat.nLength = sizeof(SECURITY_ATTRIBUTES);sat.bInheritHandle = true;sat.lpSecurityDescriptor = nullptr;if(!CreatePipe(&hRead1,&hWrite1,&sat,0)){sLog = "管道1创建失败...";return false;}if(!CreatePipe(&hRead2,&hWrite2,&sat,0)){sLog = "管道2创建失败...";CloseHandle(hRead1);CloseHandle(hWrite1);return false;}

创建进程并重定向

STARTUPINFO startupinfo;startupinfo.cb = sizeof(STARTUPINFO);GetStartupInfo(&startupinfo);startupinfo.hStdError = hWrite2;startupinfo.hStdOutput = hWrite2;startupinfo.hStdInput = hRead1;startupinfo.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;startupinfo.wShowWindow = SW_HIDE;PROCESS_INFORMATION pinfo;std::string sCmd = "plink.exe -ssh -P 22 test@192.168.2.10";if(!CreateProcess(NULL, (LPSTR)sCmd.c_str(), NULL, NULL, TRUE, NULL, NULL, NULL, &startupinfo, &pinfo)){sLog = "进程创建失败...";CloseHandle(hRead1);CloseHandle(hWrite1);CloseHandle(hRead2);CloseHandle(hWrite2);return false;}CloseHandle(pinfo.hThread);CloseHandle(pinfo.hProcess);

发送数据

DWORD byteWrite = 0;sCmd = "help\r\n";WriteFile(hWrite1, sCmd.c_str(), sCmd.length(), &byteWrite, NULL); if(byteWrite == sCmd.length())return true;elsereturn false;

读取数据

读之前应先查看管道是否有数据

DWORD byteRead; if(!PeekNamedPipe(hRead2,NULL,0,NULL,&byteRead,NULL)){return false;}if(byteRead <= 0){sLog = "管道无数据\n";return true;}char buffer[1024] = {0};         ReadFile(hRead2, buffer, 4095, &byteRead, NULL);