检测stdin是终端还是管道?

Mik*_*aid 108 c c++ qt stdin pipe

当我python从没有参数的终端执行" "时,它会启动Python交互式shell.

当我cat | python从终端执行" "时,它不会启动交互模式.不知何故,没有得到任何输入,它已检测到它已连接到管道.

我如何在C或C++或Qt中进行类似的检测?

Ric*_*dle 132

用途isatty:

#include <stdio.h>
#include <io.h>
...    
if (isatty(fileno(stdin)))
    printf( "stdin is a terminal\n" );
else
    printf( "stdin is a file or a pipe\n");
Run Code Online (Sandbox Code Playgroud)

(在Windows上,它们以下划线为前缀:_isatty,_fileno)

  • 在POSIX上没有`io.h`和`isatty()`你需要包含`unistd.h`. (49认同)
  • +1:stdin可以是管道或从文件重定向.最好检查它是否*是交互式的,而不是检查它是否*不是*. (12认同)
  • 注意:如果你想查看你的 -output- 是否是 tty,你需要检查 stdout (STDOUT_FILENO),以防你想在通过管道传输到 `less` 时抑制输出。 (2认同)

max*_*zig 66

摘要

对于许多用例,POSIX函数isatty()是检测stdin是否连接到终端所需的全部功能.一个最小的例子:

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

int main(int argc, char **argv)
{
  if (isatty(fileno(stdin)))
    puts("stdin is connected to a terminal");
  else
    puts("stdin is NOT connected to a terminal");
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

以下部分比较了在必须测试不同程度的交互性时可以使用的不同方法.

方法详解

有几种方法可以检测程序是否以交互方式运行.下表显示了概述:

cmd\method             ctermid    open   isatty   fstat
????????????????????????????????????????????????????????????
./test                 /dev/tty   OK     YES      S_ISCHR
./test ? test.cc       /dev/tty   OK     NO       S_ISREG
cat test.cc | ./test   /dev/tty   OK     NO       S_ISFIFO
echo ./test | at now   /dev/tty   FAIL   NO       S_ISREG

结果来自使用以下程序的Ubuntu Linux 11.04系统:

#include <stdio.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <termios.h>
#include <unistd.h>
#include <iostream>
using namespace std;
int main() {
  char tty[L_ctermid+1] = {0};
  ctermid(tty);
  cout << "ID: " << tty << '\n';
  int fd = ::open(tty, O_RDONLY);
  if (fd < 0) perror("Could not open terminal");
  else {
    cout << "Opened terminal\n";
    struct termios term;
    int r = tcgetattr(fd, &term);
    if (r < 0) perror("Could not get attributes");
    else cout << "Got attributes\n";
  }
  if (isatty(fileno(stdin))) cout << "Is a terminal\n";
  else cout << "Is not a terminal\n";
  struct stat stats;
  int r = fstat(fileno(stdin), &stats);
  if (r < 0) perror("fstat failed");
  else {
    if (S_ISCHR(stats.st_mode)) cout << "S_ISCHR\n";
    else if (S_ISFIFO(stats.st_mode)) cout << "S_ISFIFO\n";
    else if (S_ISREG(stats.st_mode)) cout << "S_ISREG\n";
    else cout << "unknown stat mode\n";
  }
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

终极设备

如果交互式会话需要某些功能,您可以打开终端设备并(暂时)设置所需的终端属性tcsetattr().

Python示例

该决定是否解释运行Python代码交互使用isatty().功能PyRun_AnyFileExFlags()

/* Parse input from a file and execute it */

int
PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
                     PyCompilerFlags *flags)
{
    if (filename == NULL)
        filename = "???";
    if (Py_FdIsInteractive(fp, filename)) {
        int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
Run Code Online (Sandbox Code Playgroud)

电话 Py_FdIsInteractive()

/*
 * The file descriptor fd is considered ``interactive'' if either
 *   a) isatty(fd) is TRUE, or
 *   b) the -i flag was given, and the filename associated with
 *      the descriptor is NULL or "<stdin>" or "???".
 */
int
Py_FdIsInteractive(FILE *fp, const char *filename)
{
    if (isatty((int)fileno(fp)))
        return 1;
Run Code Online (Sandbox Code Playgroud)

哪个叫isatty().

结论

有不同程度的互动性.检查是否stdin连接到管道/文件或真实终端isatty()是一种自然的方法.


Eri*_*ski 8

可能他们正在检查“stdin”与 fstat 的文件类型,如下所示:

struct stat stats;
fstat(0, &stats);
if (S_ISCHR(stats.st_mode)) {
    // Looks like a tty, so we're in interactive mode.
} else if (S_ISFIFO(stats.st_mode)) {
    // Looks like a pipe, so we're in non-interactive mode.
}
Run Code Online (Sandbox Code Playgroud)

当然,Python 是开源的,所以你只要看看他们做了什么就可以确定:

http://www.python.org/ftp/python/2.6.2/Python-2.6.2.tar.bz2


Gle*_*les 5

在 Windows 上,您可以使用 GetFileType。

HANDLE hIn = GetStdHandle(STD_INPUT_HANDLE);
DWORD type = GetFileType(hIn);
switch (type) {
case FILE_TYPE_CHAR: 
    // it's from a character device, almost certainly the console
case FILE_TYPE_DISK:
    // redirected from a file
case FILE_TYPE_PIPE:
    // piped from another program, a la "echo hello | myprog"
case FILE_TYPE_UNKNOWN:
    // this shouldn't be happening...
}
Run Code Online (Sandbox Code Playgroud)