加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

delphi – 与平台无关的方法来检查是否可以安全地使用Writeln到O

发布时间:2020-12-15 09:12:36 所属栏目:大数据 来源:网络整理
导读:对于具有OSX和 Android支持的较新的Delphi版本,是否有一种独立于平台的方法来检测 Writeln到 Output是否可以安全使用? 输出文档包含一个说明 Most processes do not have a standard output file,and writing to Output raises an error. Delphi programs h
对于具有OSX和 Android支持的较新的Delphi版本,是否有一种独立于平台的方法来检测 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;

所以问题可以改写:“如果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 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.

因此,如果对应于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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读