1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
|
// Execute the file while capturing output and show it on memo
bool launchExe(AnsiString exe, AnsiString param, const TMemo* log)
{
bool result = false;
// We use pipes to capture the program output
SECURITY_DESCRIPTOR sd;
SECURITY_ATTRIBUTES sa;
InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION);
SetSecurityDescriptorDacl(&sd, true, NULL, false);
sa.nLength = sizeof sa;
sa.bInheritHandle = true;
sa.lpSecurityDescriptor = &sd;
HANDLE hReadPipe, hWritePipe;
CreatePipe(&hReadPipe, &hWritePipe, &sa, 2500000);
STARTUPINFO si;
memset(&si, 0, sizeof si); // default values for all structure members = 0
si.cb = sizeof si;
si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
si.wShowWindow = SW_HIDE; // hide the window (console application)
si.hStdOutput = hWritePipe;
si.hStdError = hWritePipe;
PROCESS_INFORMATION pi;
DWORD exitcode = 0;
AnsiString cmdLine = shortPath(exe) + " " + param;
if (CreateProcess(NULL, cmdLine.c_str(), NULL, NULL, true, 0, NULL, NULL, &si, &pi)) {
WaitForSingleObject(pi.hProcess, 90000); // wait for the external program to terminate
CloseHandle(pi.hThread); // with a timeout = 1 min 30 sec
GetExitCodeProcess(pi.hProcess, &exitcode);
// if the application wrote something to stdout (--> our pipe), grab it
if (GetFileSize(hReadPipe, NULL) > 0) {
DWORD bytesRead;
char buffer[4000];
bool moreData = false;
while (!moreData) {
memset(&buffer, 0, 4000);
ReadFile(hReadPipe, &buffer, 4000, &bytesRead, NULL);
log->Lines->Add(AnsiString(buffer));
if (bytesRead < 4000) moreData = true; else moreData = false;
}
}
}
if (exitcode != 0) result = false; else result = true;
return result;
} |
Partager