標準入出力(stdio) が TeleTYpe かどうか調べる関数
実行例
- KBDAHOLIC - やぬすさんとこ / 2010-02-19: C/C++ で redirection と pipeline を検知する方法
- ファイヤープロジェクト / 2003-07-20: リダイレクトされているかどうか知りたい
#include <stdio.h> #include <stdlib.h> #ifdef _WIN32 #include <io.h> #define TTY "CON:" #else #include <unistd.h> #define TTY "/dev/tty" #endif int main() { FILE *ttyin; FILE *ttyout; int x = -1; int y = -1; ttyin = fopen(TTY, "r"); if (ttyin == NULL) { fprintf(stderr, "Error: can not read open file: %s\n", TTY); return EXIT_FAILURE; } ttyout = fopen(TTY, "w"); if (ttyout == NULL) { fprintf(stderr, "Error: can not write open file: %s\n", TTY); return EXIT_FAILURE; } fscanf(stdin, "%d", &x); fscanf(ttyin, "%d", &y); fprintf(stdout, "stdout: %d %d %d %d %d\n", isatty(fileno(stdin)), isatty(fileno(stdout)), isatty(fileno(stderr)), x, y); fprintf(stderr, "stderr: %d %d %d %d %d\n", isatty(fileno(stdin)), isatty(fileno(stdout)), isatty(fileno(stderr)), x, y); fprintf(ttyout, "ttyout: %d %d %d %d %d\n", isatty(fileno(stdin)), isatty(fileno(stdout)), isatty(fileno(stderr)), x, y); fclose(ttyout); fclose(ttyin); return EXIT_SUCCESS; }
$ gcc isatty.c $ echo 3 | ./a 5 stdout: 0 1 1 3 5 stderr: 0 1 1 3 5 ttyout: 0 1 1 3 5 $ ./a &>/dev/null 3 5 ttyout: 1 0 0 3 5 $ ./a >/dev/null 3 5 stderr: 1 0 1 3 5 ttyout: 1 0 1 3 5 $ ./a 2>/dev/null 3 5 stdout: 1 1 0 3 5 ttyout: 1 1 0 3 5
タグ
コメントをかく