简体   繁体   中英

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). 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). The three file descriptors are the same file opened 3 times (possibly with different options).

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.

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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