检测 NUL 文件描述符(isatty 是假的) [英] Detect NUL file descriptor (isatty is bogus)

查看:41
本文介绍了检测 NUL 文件描述符(isatty 是假的)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下 C 文件在通过管道传输 NUL 时给出了一个虚假的结果:

The following C file gives a bogus result when NUL is piped to it:

int main()
{
  printf("_isatty = %d\n", _isatty(0));
}

结果是:

C:\Users\Edward\Dev\nulltest> test.exe < NUL
_isatty = 64

我很确定 NUL(又名/dev/null)不是终端设备!所以我需要以另一种方式检测文件描述符是否对应于 NUL.该数字没有任何特定含义;当我确实连接了一个终端时,我会看到它.

I'm pretty sure NUL (aka /dev/null) is not a terminal device! So I need to detect in another way whether or not the file descriptor corresponds to NUL. The number doesn't have any specific meaning; I see it when I actually do have a terminal attached.

我该怎么办?这个问题建议使用一个粗略的未记录函数来获取底层名称,大概是将其与 NUL 进行比较,但这对我来说感觉不太理想.有没有更好的办法?

What should I do? This question suggests using a sketchy undocumented function to get the underlying name, presumably comparing it to NUL, but that feels less than ideal to me. Is there a better way?

附言这将有助于解决这个 GHC 错误.

推荐答案

来自 msdn:

_isatty 如果描述符与字符设备.否则,_isatty返回 0.

_isatty returns a nonzero value if the descriptor is associated with a character device. Otherwise, _isatty returns 0.

NUL 就像 Unix 上的/dev/null,它是一个字符设备.

NUL is like /dev/null on Unix, it's a char device.

请注意,在 Linux 上,isatty 是不同的:

Note that on Linux, isatty is different:

isatty() 函数测试是否 fd是一个打开的文件描述符引用到终端.

The isatty() function tests whether fd is an open file descriptor referring to a terminal.

您可以做的是尝试将 STDIN_FILENO (0) 与 ${cwd}/NUL(使用 stat 或 stat)进行比较.

What you can do is try to compare STDIN_FILENO (0) with ${cwd}/NUL (using stat or stat).

更新:

int ret = GetFileType(GetStdHandle(STD_INPUT_HANDLE));

它将为 NUL 或 tty 返回 FILE_TYPE_CHAR.

It will return FILE_TYPE_CHAR for NUL or tty.

有关其他信息,请参阅 GetFileType 文档值.您可以检测文件/字符设备/管道.

See GetFileType documentation for other values. You can detect files/char device/pipes.

更新最终版:

使用 GetConsoleMode输入和 GetConsoleScreenBufferInfo 用于输出.>

Use GetConsoleMode for input and GetConsoleScreenBufferInfo for output.

CONSOLE_SCREEN_BUFFER_INFO sbi;
DWORD mode;
if (!GetConsoleMode(GetStdHandle(STD_INPUT_HANDLE), &mode))
   fprintf(stderr, "not console\n");
else
   fprintf(stderr, "console\n");
if (!GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &sbi))
   fprintf(stderr, "not console\n");
else
  fprintf(stderr, "console\n");

这篇关于检测 NUL 文件描述符(isatty 是假的)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆