[fpc-devel] StdOut capture for FPC RTL

Tomas Hajny XHajT03 at hajny.biz
Fri Nov 26 18:59:49 CET 2010

On Thu, November 25, 2010 18:57, Jonas Maebe wrote:
> On 25 Nov 2010, at 13:21, Jonas Maebe wrote:
>> On 25 Nov 2010, at 12:24, Anton Kavalenka wrote:
>>> What I have to do to properly initialize these defaults for new threads
>>> AFTER capturing StdOut?
>> Store a copy of your stdout in a global variable, and after creating a
>> new thread
>>  close(stdout);
>>  stdout:=myglobalstdout;
>> (and maybe the same for "output").
> Actually, that won't work because the different threads will then work on
> a common buffer but with distinct pointers into it. A better solution is
> probably to do this in the intialisation code of each thread instead:
> {$ifdef unix}
>   fpclose(ttextrec(stdout).handle);
> {$elsif defined(MSWINDOWS)}
>   { this is a copy of do_close() from the rtl, I don't know whether
>     a new handle from a thread can actually have any of these values }
>   if (handle <> StdInputHandle) and
>      (handle <> StdOutputHandle) and
>      (handle <> StdErrorHandle) then
>     CloseHandle(ttextrec(stdout).handle);
> {$else}
>   {$error Add support for this platform}
> {$endif}
> ttextrec(stdout).handle:=myglobalstdouthandle;

I'm not sure if closing the handle using the platform specific API is
actually a good idea here, because the RTL is probably not opening the
file in this case and trying to close it multiple times (in different
threads) may have unwanted effects (it would result in a failure return
code probably).

BTW, other alternative solutions for the original problem (not necessarily
fitting your needs, just for completeness sake):

- Perform the writes always in one and the same thread dedicated for that
purpose (i.e. have the other threads communicate to that thread using some
sort of inter-thread communication).

- Don't write to stdout but write to your own global (text) variable
instead while ensuring that only one thread is accessing the variable at a
time by your own means.

- Alternative of the above - override Write / WriteLn by your own routine
doing one of the former two.


More information about the fpc-devel mailing list