c++ - 如何检查我的程序是否有数据通过管道传输到其中

标签 c++ c pipe stdin

我正在编写一个应该通过标准输入读取输入的程序,所以我有以下结构。

FILE *fp=stdin;

但是如果用户没有将任何东西传送到程序中,这就会挂起,我如何检查用户是否真的像管道一样将数据传送到我的程序中

gunzip -c file.gz |./a.out #should work
./a.out  #should exit program with nice msg.

谢谢

最佳答案

由于您使用的是文件指针,因此您需要 isatty()fileno() 来执行此操作:

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

int main(int argc, char* argv[])
{
    FILE* fp = stdin;

    if(isatty(fileno(fp)))
    {
        fprintf(stderr, "A nice msg.\n");
        exit(1);
    }

    /* carry on... */
    return 0;
}

实际上,这是很长的路要走。简短的方法是不使用文件指针:

#include <unistd.h>

int main(int argc, char* argv[])
{
    if(isatty(STDIN_FILENO))
    {
        fprintf(stderr, "A nice msg.\n");
        exit(1);
    }

    /* carry on... */
    return 0;
}

几个标准的 Unix 程序执行此检查以修改它们的行为。例如,如果您将 ls 设置为提供漂亮的颜色,那么如果您将其标准输出通过管道传输到另一个程序,它将关闭这些颜色。

关于c++ - 如何检查我的程序是否有数据通过管道传输到其中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2564503/

相关文章:

c - C 中进程之间的管道

c++ - 需要在动态数组中存储 n 个数字

C程序时间转换

c++ - boost::asio 数据包顺序和连续性

c - 为什么这些构造使用增量前和增量后未定义的行为?

c - 使用 scanf 读取无符号字符

linux - 在 Linux shell (Bash) 中使用命名管道的示例

delphi - Delphi 中用于命令提示符的管道

c++ - 了解多重继承中的虚拟表

c++ - 迭代器类别' : is not a member of any base class of 'std::iterator_traits<_InIt>'