【问题标题】:How can we distinguish that input to our program is directed or it is just a user's input by using isatty function?我们如何通过使用 isatty 函数来区分对我们程序的输入是定向的还是只是用户的输入?
【发布时间】:2014-03-05 00:23:48
【问题描述】:

我在这个链接上的 Stack Overflow 上问了一个类似的问题:

Why is it that we can redirect the input of 'less' command, but we can't run less without any arguments?

这导致我这样做:
我们如何区分我们程序的输入是定向的还是只是用户的输入?!
谁能给我一个关于如何使用isatty 函数的小例子?

【问题讨论】:

  • 为了完整起见,您应该在问题中添加您询问 isatty() 的原因。

标签: shell input


【解决方案1】:

isatty 的示例:

#include <unistd.h>
#include <stdio.h>

int main()
{
  if( isatty(STDIN_FILENO) )
    puts("Connected to a terminal");
  else
    puts("Not connected to a terminal");

  return 0;
}

使用中:

$ gcc isatty.c 
$ ./a.out 
Connected to a terminal
$ echo hello | ./a.out 
Not connected to a terminal

没有比这更简单的了!

【讨论】:

  • 哇,这很简单 :D 它将解决我的问题,谢谢。顺便说一句,我们所说的 “连接到终端”“未连接到终端” 到底是什么意思?!我的意思是,我们什么时候说程序连接到终端,什么时候没有!
  • @Shnd 严格来说,除非我们使用特别旧的硬件,否则它永远不会连接到终端。在大型机普及的时代,真正的终端与计算机是分开的。如今它们只是在软件中实现,这就是tty 设备的全部意义所在。请参阅此 Q(此处为第二个最受好评的 Q!)以获取更多信息 - unix.stackexchange.com/questions/4126/…
  • 我今天学到了很多。感谢@Graeme 的宝贵时间。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-13
  • 2021-05-30
  • 1970-01-01
  • 1970-01-01
  • 2019-11-23
相关资源
最近更新 更多