【问题标题】:Piping input to stdin does not work in c管道输入到标准输入在 c 中不起作用
【发布时间】:2015-12-16 10:17:59
【问题描述】:
#include<stdio.h>

main()
{
    int count;
    fprintf(stderr, "Starting program.\n");
    scanf("%d", &count);
    fprintf(stderr, "Read: %d\n", count);

}

我只是想从 stdin 读取一个数字并在 stderr 上重复它,当我编译和运行时,我看到第一个 stderr 打印,然后按预期看到代码块,但是当我将输入管道输入到程序时,我从来没有看到stderr 打印,程序立即退出。

我尝试在最后一次打印到 stderr 后添加一个 sleep(5),但程序立即退出,没有任何输出。

gcc pipetest.c -o b
echo '2'  > ./b

【问题讨论】:

  • 试试echo 2 | ./b
  • 同样的结果,程序结束,没有任何反应。
  • 重拍b后重试。
  • 谢谢!介意解释一下这里到底发生了什么?
  • | is pipe (program1 | program2) program1's stdout connect to program2's stdin, > is redirect (program > filename: program's stdout write to file, stdout redirect to file), echo '2' &gt; ./b 表示将'2'写入b的文件。

标签: c pipe stdin stderr


【解决方案1】:

试试下面的代码

echo 2|./b

 #include <stdio.h>
 #include <unistd.h>
 #include <termios.h>
 int
 main(void)
 {
   int  count;
   struct termios t;
   if (tcgetattr(STDIN_FILENO, &t) < 0)
   {   
     scanf("%d", &count);
     fprintf(stderr, "Read: %d\n", count);
     return 0;
   }
   fprintf(stderr, "no pipe found \n");
   return -1; 
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-26
    • 2012-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-09
    • 1970-01-01
    • 2020-05-11
    相关资源
    最近更新 更多