// testcrePro.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" /* int _tmain(int argc, _TCHAR* argv[]) { return 0; } */ #include <iostream> #include <windows.h> #include <Shlwapi.h> using namespace std; #define BUFSIZE 4096 int main() { BOOL bRet = FALSE; DWORD dwRead = 0; DWORD dwAvail = 0; char cbBuf[4096] = { 0 }; HANDLE hReadPipe = NULL; HANDLE hWritePipe = NULL; SECURITY_ATTRIBUTES sa; sa.nLength = sizeof(sa); sa.bInheritHandle = TRUE; sa.lpSecurityDescriptor = NULL; TCHAR *pCommandLine = new TCHAR[0x200];// //char szPath[] = "C:\\Windows\\System32\\calc.exe"; TCHAR szPath[] = _T("ping 192.168.5.1 -t"); CreatePipe(&hReadPipe, &hWritePipe, &sa, 0); STARTUPINFO si = { 0 }; si.cb = sizeof(STARTUPINFO); GetStartupInfo(&si); si.wShowWindow = SW_HIDE; si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES; si.hStdError = hWritePipe; si.hStdOutput = hWritePipe; PROCESS_INFORMATION pi = { 0 }; memset(pCommandLine, 0, sizeof(szPath)); lstrcpy(pCommandLine, szPath); if (!CreateProcess(NULL, pCommandLine, NULL, NULL, TRUE, NULL, NULL, NULL, &si, &pi))//创建子进程 { if (pCommandLine) delete pCommandLine; CloseHandle(pi.hProcess); CloseHandle(pi.hThread); CloseHandle(hReadPipe); CloseHandle(hWritePipe); return 1; } std::string strResult; do { cout << "test.." << endl; /* if (!PeekNamedPipe(hReadPipe, NULL, NULL, &dwRead, &dwAvail, NULL) || dwAvail <= 0)//PeekNamePipe用来预览一个管道中的数据,用来判断管道中是否为空 { break; }*/ if (ReadFile(hReadPipe, cbBuf, BUFSIZE, &dwRead, NULL))//这里是读管道,即便已经没有数据,仍然会等待接收数据,因为,子进程会认为父进程仍有数据要发送,只是暂时没法送, { //所以,会“卡”在这里。所以才需要PeekNamePipe if (dwRead == 0) break; cout << dwRead << endl; cout << cbBuf << endl; } } while (TRUE); if (pCommandLine) delete pCommandLine; cout << "delete" << endl; CloseHandle(pi.hProcess); CloseHandle(pi.hThread); CloseHandle(hReadPipe); CloseHandle(hWritePipe); return 0; }
标签:调用,windows,TCHAR,si,hWritePipe,多进,sa,NULL,pCommandLine From: https://www.cnblogs.com/cnchengv/p/16738708.html