对于较新的 Delphi 版本,支持 OSX 和 Android,是否有一种独立于平台的方法来检测 Writeln至 Output可以安全使用吗?
输出文档包含一条注释
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;
<小时/>
因此问题可以改写为:“如果 Output 为 True,Delphi 应用程序能否始终安全地使用 IsConsole?”。
由于它是一种后备日志方法,因此如果日志消息“不可见”(重定向到/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 function
int 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.
因此,如果与控制台输出相对应的流的 fileno
的平台独立请求返回 2 或 1,则您不会被重定向,如果它返回 -1,则您的输出没有结束
对于 Delphi、Free Pascal、Virtual Pascal 和 GNU Pascal,确切的代码可能会有所不同。 查看您感兴趣的目标平台的运行时库,例如
关于delphi - 与平台无关的方法来检查 Writeln to Output 是否可以安全使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23287196/