Redmon&用Delphi捕获stdin

时间:2011-12-08 15:12:22

标签: delphi console-application

我正在使用redmon将postscript重定向到delphi进行处理。

我使用以下代码将stdin读取到文件中:

var
  Stdin: THandleStream;
  FStream: TFileStream;
  BytesRead:Int64;
  Buffer: array[0..1023] of Byte; 

StdIn := THandleStream.Create(GetStdHandle(STD_INPUT_HANDLE));
try
  tempps:=GetTempFile('.ps');
  FStream:=tfilestream.Create(tempps,fmCreate or fmOpenReadWrite);
  StdIn.Seek(0,0);
  try
    repeat
      BytesRead:=StdIn.Read(Buffer,1024);
      FStream.Write(Buffer,BytesRead);
    until bytesread<SizeOf(Buffer);
  finally
    InputSize:=FStream.Size;
    FStream.Free;
  end;
finally
  StdIn.Free;
end;

这适用于大多数情况,但redmon日志文件显示的情况除外:

REDMON WritePort: OK  count=65536 written=65536

REDMON WritePort: Process not running. Returning TRUE.
    Ignoring 65536 bytes

事实上它是65536只是一个红鲱鱼,这是因为我没有正确阅读stdin,或者在某个我忽略的地方有一些奇怪的限制?

提前致谢。

编辑1

65536是一个红色的鲱鱼 - redmon在日志中每64k打印一条消息,整个文件是688759字节,但是看起来像redmon关闭输出的早期,但是仍然继续输出更多的文本。

1 个答案:

答案 0 :(得分:3)

我不知道RedMon是如何工作的,但我不会依赖bytesread<SizeOf(Buffer)作为EOF条件,因为我认为你实际上是在读取管道,并且ReadFile函数正如MSDN文档所说的那样如果从管道读取,则返回读取的字节数小于要读取的字节数。

BytesRead <= 0条件更可靠(只有当RedMon在管道的另一端写入0个字节时它才会失败,我想它不应该这样做):

repeat
  BytesRead:=StdIn.Read(Buffer,1024);
  if BytesRead > 0 then
    FStream.WriteBuffer(Buffer,BytesRead);
until BytesRead <= 0;