Определить, является ли stdin терминалом или каналом?

Когда я выполнюpython"из терминала без аргументов выводит интерактивную оболочку Python.

Когда я выполнюcat | python"из терминала он не запускает интерактивный режим. Каким-то образом, не получив никакого ввода, он обнаружил, что он подключен к каналу.

Как бы я сделал подобное обнаружение в C или C++ или Qt?

6 ответов

Решение

Использование 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");

(На окнах они имеют префикс подчеркивания: _isatty, _fileno)

Резюме

Для многих случаев использования функция 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;
}

В следующем разделе сравниваются различные методы, которые можно использовать, если необходимо проверить различные степени интерактивности.

Методы в деталях

Есть несколько способов определить, работает ли программа в интерактивном режиме. Следующая таблица показывает обзор:

cmd \ method ctermid open isatty fstat
-------------------------------------------------- ----------./test                 /dev/tty   OK     YES      S_ISCHR
./test ≺ test.cc       /dev/tty   OK НЕТ S_ISREG
кошка test.cc | ./test   /dev/tty   OK НЕТ S_ISFIFO
эхо./test | сейчас /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;
}

Срок устройства

Если интерактивный сеанс требует определенных возможностей, вы можете открыть терминальное устройство и (временно) установить необходимые атрибуты терминала через 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);

звонки 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;

какие звонки isatty(),

Заключение

Есть разные степени интерактивности. Для проверки, если stdin подключен к каналу / файлу или реальному терминалу isatty() это естественный способ сделать это.

Вероятно, они проверяют тип файла "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.
}

Но зачем спрашивать нас? Python с открытым исходным кодом. Вы можете просто посмотреть, что они делают, и точно знать:

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

Надеюсь, это поможет,

Эрик Мелски

В 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...
}

Вызовите stat() или fstat() и посмотрите, установлен ли S_IFIFO в st_mode.

Ты можешь позвонить stat(0, &result) и проверить на !S_ISREG( result.st_mode ), Это Posix, а не C/C++.

Другие вопросы по тегам