Главная страница
    Top.Mail.Ru    Яндекс.Метрика
Форум: "WinAPI";
Текущий архив: 2003.04.17;
Скачать: [xml.tar.bz2];

Вниз

Написал процедуру чтения вывода консольного приложения:   Найти похожие ветки 

 
Alexander   (2003-02-19 11:44) [0]


function CreateDOSProcessRedirected3(const CommandLine, OutputFile: string): Boolean;
var
pCommandLine: array[0..MAX_PATH] of Char;
pTemp: array[0..MAX_PATH] of Char;
SI: TStartupInfo;
PI: TProcessInformation;
SecAtrrs: TSecurityAttributes;

hRead, hWrite, BytesRead: Cardinal;
begin
{ copy the parameter Pascal strings to null terminated strings }
StrPCopy(pCommandLine, CommandLine);

try
FillChar(SecAtrrs, SizeOf(SecAtrrs), #0);
SecAtrrs.nLength := SizeOf(SecAtrrs);
SecAtrrs.lpSecurityDescriptor := nil;
SecAtrrs.bInheritHandle := True;

CreatePipe(hRead, hWrite, @SecAtrrs, 0);

{ prepare StartupInfo structure }
FillChar(SI, SizeOf(SI), #0);
SI.cb := SizeOf(SI);
SI.dwFlags := STARTF_USESHOWWINDOW or STARTF_USESTDHANDLES;
SI.wShowWindow := SW_HIDE;
SI.hStdOutput := hWrite;

{ create the app }
Result := CreateProcess(nil, { pointer to name of executable module }
pCommandLine, { pointer to command line string }
nil, { pointer to process security attributes }
nil, { pointer to thread security attributes }
True, { handle inheritance flag }
CREATE_NEW_CONSOLE or REALTIME_PRIORITY_CLASS, { creation flags }
nil, { pointer to new environment block }
nil, { pointer to current directory name }
SI, { pointer to STARTUPINFO }
PI); { pointer to PROCESS_INF }

{ wait for the app to finish its job and take the handles to free them later }
CloseHandle(PI.hProcess);
CloseHandle(PI.hThread);
finally
end;
while True do
begin
if not ReadFile(hRead, pTemp, 255, BytesRead, nil) or (BytesRead = 0) then
Break;
Form1.Memo1.Lines.Add(pTemp);
end;
CloseHandle(hRead);
end;


Вопросы:
1. в последнем цикле чтения из пайпа не останавливается. Как там правильно завершить?
2. вывод в консоль производится на русском, а я получаю абракадабру: как преобразовать в русский?


 
Alexander   (2003-02-19 11:47) [1]

Ещё вопрос:
3. если консольное приложение будет долго писать - нормально эта функция отработает, или надо добывлять что-то вида: WaitForSingleObject(PI.hProcess, INFINITE); ?


 
Alexander   (2003-02-19 16:49) [2]

Так, со всеми вопросами сам разобрался, вот что в итоге получилось:

function CreateDOSProcess(const CommandLine: string): Boolean;
var
pCommandLine: array[0..MAX_PATH] of Char;
pTemp: array[0..255] of Char;
SI: TStartupInfo;
PI: TProcessInformation;
SA: TSecurityAttributes;

hRead, hWrite, BytesRead, i: Cardinal;
Line: string;
PrevChar: Char;
begin
Result := False;
StrPCopy(pCommandLine, CommandLine);

ZeroMemory(@SA, SizeOf(TSecurityAttributes));
SA.nLength := SizeOf(TSecurityAttributes);
SA.bInheritHandle := True;

if CreatePipe(hRead, hWrite, @SA, 0) then
begin
ZeroMemory(@SI, SizeOf(SI));
SI.cb := SizeOf(SI);
SI.dwFlags := STARTF_USESHOWWINDOW or STARTF_USESTDHANDLES;
SI.wShowWindow := SW_HIDE;
SI.hStdOutput := hWrite;
SI.hStdError := hWrite;

Result := CreateProcess(nil, pCommandLine, nil, nil, True,
CREATE_NEW_CONSOLE, nil, nil, SI, PI);

CloseHandle(hWrite);

Line := "";
PrevChar := #0;
while ReadFile(hRead, pTemp, 256, BytesRead, nil) do
begin
OemToAnsi(pTemp, pTemp);
i := 0;
while (i < BytesRead) do
begin
if not (PrevChar = #13) or not (pTemp[i] = #10) then
begin
PrevChar := #0;
while (pTemp[i] <> #13) and (i < BytesRead) do
begin
Line := Line + pTemp[i];
Inc(i);
end;
end;
if (i < BytesRead) then
if ((i + 1) < BytesRead) then
begin
if ((pTemp[i] = #13) and (pTemp[i + 1] = #10)) or ((PrevChar = #13) and (pTemp[i] = #10)) then
begin
Form1.Memo1.Lines.Add(Line);
if ((pTemp[i] = #13) and (pTemp[i + 1] = #10)) then
Inc(i, 2)
else
Inc(i, 1);
Line := "";
end;
end
else
begin
if (pTemp[i] = #13) then
PrevChar := #13
else
PrevChar := #0;
Inc(i);
end;
end;
end;
CloseHandle(hRead);
CloseHandle(PI.hProcess);
CloseHandle(PI.hThread);
end;
end;


Всё работает нормально и построчно заносится в memo, но ...
для Windows 98 зависает при операции FileRead() (выделено) когда я даю команду, например "subst /?" а в Windows 2000 эта команда обрабатывается нормально (как, впрочем, и все остальные).


 
MBo   (2003-02-19 17:04) [3]

поищи TDosMemo или DosCommand



Страницы: 1 вся ветка

Форум: "WinAPI";
Текущий архив: 2003.04.17;
Скачать: [xml.tar.bz2];

Наверх





Память: 0.46 MB
Время: 0.021 c
1-54637
baracuda
2003-04-07 20:20
2003.04.17
outlook


11-54541
Vitalis
2002-07-02 16:22
2003.04.17
Вопросы по TKOLHTTP и UWrd


14-54858
Duke DEE
2003-04-01 18:37
2003.04.17
TNMHTTP???


1-54578
Zull
2003-04-07 07:29
2003.04.17
Генератор случайных чисел


1-54638
Serj
2003-04-04 12:47
2003.04.17
Обработка нажатия клавиши в ComboBox





Afrikaans Albanian Arabic Armenian Azerbaijani Basque Belarusian Bulgarian Catalan Chinese (Simplified) Chinese (Traditional) Croatian Czech Danish Dutch English Estonian Filipino Finnish French
Galician Georgian German Greek Haitian Creole Hebrew Hindi Hungarian Icelandic Indonesian Irish Italian Japanese Korean Latvian Lithuanian Macedonian Malay Maltese Norwegian
Persian Polish Portuguese Romanian Russian Serbian Slovak Slovenian Spanish Swahili Swedish Thai Turkish Ukrainian Urdu Vietnamese Welsh Yiddish Bengali Bosnian
Cebuano Esperanto Gujarati Hausa Hmong Igbo Javanese Kannada Khmer Lao Latin Maori Marathi Mongolian Nepali Punjabi Somali Tamil Telugu Yoruba
Zulu
Английский Французский Немецкий Итальянский Португальский Русский Испанский