简体   繁体   English

从stderr而不是stdin读取

[英]Reading from stderr instead of stdin

I ran into code like this in the wild, and I'm wondering why this works. 我在野外遇到了这样的代码,我想知道为什么这样做有效。 The code reads from stderr (fd==2) instead of stdin (fd==0). 该代码从stderr(fd == 2)而不是stdin(fd == 0)读取。 The wierd thing is this actually works somewhat. 奇怪的是,这实际上有点用。 You can read typing at the console, but not piped input. 您可以在控制台上阅读打字,但不能通过管道输入。 Any idea what is going on here? 知道这里发生了什么吗?

#include <stdio.h>
#include <unistd.h>
int main(){
   char buf[15];
   int nchars=read(2,buf,15);
   printf("%d '%s'\n",nchars,buf);
}

Good question! 好问题! This works because when you are at the console in the terminal, STDIN, STDOUT, and STDERR all ultimately point to the same resource: /dev/tty (or whatever your platform calls it). 之所以可以这样做是因为,当您在终端的控制台中时,STDIN,STDOUT和STDERR最终都指向同一资源: /dev/tty (或您的平台所调用的任何东西)。 The three file descriptors are the same file opened 3 times (possibly with different options). 这三个文件描述符是同一文件打开3次(可能具有不同的选项)。

When you pipe content, that is no longer the case and this broken code no longer works since stdin is now one thing while stdout/stderr is another. 当您通过管道传输内容时,情况已不再如此,并且此破碎的代码不再起作用,因为stdin现在是一回事,而stdout / stderr是另一回事。

In your code sample it makes no sense to do so and would be best described as a bug. 在您的代码示例中,这样做是没有意义的,最好将其描述为错误。 But perhaps the author of that "code in the wild" was trying to do something different and had his or her reasons for doing so. 但是也许那个“狂野的代码”的作者试图做一些不同的事情,并且有这样做的理由。 Do you have a reference for that code sample you found? 您是否为所找到的代码示例提供参考?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM