输出文档包含一个说明
Most processes do not have a standard output file, and writing to
Output raises an error. Delphi programs have a standard output file if
they are linked as console applications.
我的主要目标是为日志记录提供独立于平台的回退,但要避免在没有控制台(stdout)时可能出现的操作系统错误.
例如:如此检查IsConsole就足够了:
procedure Log(const Msg: string); begin if LoggingFrameworkAvailable then begin // use the logging framework to output the log message end if System.IsConsole then begin // fallback to stdout logging WriteLn(Msg); end; end;
所以问题可以改写:“如果IsConsole是真的,Delphi应用程序是否可以安全地使用Output?”.
因为它是一个后备日志方法,如果日志消息是“不可见的”(重定向到/ dev / null),只要代码保证跨平台运行而没有错误,那对我来说就没问题了.
如果是,此代码是否也可以安全地使用Free Pascal? (见Can a Windows GUI program written in Lazarus create a console and write to it at runtime?)
不是最终答案,而是写入{$IFDEF}平台相关调用平台独立POSIX C API functionint fileno(FILE * stream)
..This function returns the file descriptor associated with the stream stream. If an error is detected (for example, if the stream is not valid) or if stream does not do I/O to a file, fileno returns -1
…
There are also symbolic constants defined in unistd.h for the file descriptors belonging to the standard streams stdin, stdout, and stderr…
STDOUT_FILENO .. This macro has value 1, which is the file descriptor for standard output.
STDERR_FILENO .. This macro has value 2, which is the file descriptor for standard error output.
因此,如果对应于Console输出的流的fileno的平台独立请求返回2或1,那么您不会被重定向,如果它返回-1,那么您的输出没有结束
对于Delphi和Free Pascal以及Virtual Pascal和GNU Pascal,确切的代码可能会有所不同.
去看看您感兴趣的目标平台的运行时库,例如:
> http://svn.freepascal.org/svn/fpc/trunk/rtl/win32/system.pp
> http://svn.freepascal.org/svn/fpc/trunk/rtl/linux/system.pp