LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 772|回复: 1

如何捕捉终端窗口的输出流

[复制链接]
发表于 2003-9-19 08:47:46 | 显示全部楼层 |阅读模式
如何捕捉终端窗口的输出流
下面的Delphi例子是捕捉DOS窗口的输出流,如何用Kylix3改成Linux下的捕捉终端窗口的输出流,如运行一个Shell命令,并把结果输出到Memo中?

例子:运行 'chkdsk.exe c:\' 并且 显示其输出结果到 Memo 中!

procedure RunDosInMemo(DosApp:String;AMemo:TMemo);
const ReadBuffer = 2400;
var
Security : TSecurityAttributes;
ReadPipe,WritePipe : THandle;
start : TStartUpInfo;
ProcessInfo : TProcessInformation;
Buffer : Pchar;
BytesRead : DWord;
Apprunning : DWord;
begin
With Security do
begin
nlength := SizeOf(TSecurityAttributes);
binherithandle := true;
lpsecuritydescriptor := nil;
end;
if Createpipe (ReadPipe, WritePipe, @Security, 0) then
begin
Buffer := AllocMem(ReadBuffer + 1);
FillChar(Start,Sizeof(Start),#0);
start.cb := SizeOf(start);
start.hStdOutput := WritePipe;
start.hStdInput := ReadPipe;
start.dwFlags := STARTF_USESTDHANDLES + STARTF_USESHOWWINDOW;
start.wShowWindow := SW_HIDE;
if CreateProcess(nil,PChar(DosApp),@Security,@Security,true,NORMAL_PRIORITY_CLASS,
nil,nil,start,ProcessInfo) then
begin
repeat
Apprunning := WaitForSingleObject(ProcessInfo.hProcess,100);
Application.ProcessMessages;
until (Apprunning <> WAIT_TIMEOUT);
Repeat
BytesRead := 0;
ReadFile(ReadPipe,Buffer[0],ReadBuffer,BytesRead,nil);
Buffer[BytesRead]:= #0;
OemToAnsi(Buffer,Buffer);
AMemo.Text := AMemo.text + String(Buffer);
until (BytesRead < ReadBuffer);
end;
FreeMem(Buffer);
CloseHandle(ProcessInfo.hProcess);
CloseHandle(ProcessInfo.hThread);
CloseHandle(ReadPipe);
CloseHandle(WritePipe);
end;
end;

调用实例:RunDosInMemo('chkdsk.exe c:\',Memo1);
发表于 2003-9-19 09:59:26 | 显示全部楼层
FILE *fp;
fp = popen("ls -l", "r");
popen的第一个参数用你要运行的命令,后面直接从fp里读就行了。
您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表