关于标准输入,标准输出,标准错误

1. 为什么我们程序直接使用printf或者write(0,...)就可以输出内容,而不需要首先调用open,是因为我们的进程是shell的子进程,它直接从shell继承了文件描述符。

2.假如需要我们程序自己打开标准输入输出的话,可以这样int fd = open("/dev/tty", O_WRONLY);,需要注意的是fd的值可不一定就是0或者1,而是当前系统文件描述符未用的最小值,换句话说标准输入/输出/错误可不一定就是0/1/2。

3.为什么write(0,...)也能输出内容到屏上,按理标准输出不是fd=1吗?想想以WR方式打开一个普通文件,是不是也可以既读又写,跟此一个道理。

参照阅读:

http://bbs.chinaunix.net/thread-1376698-1-1.html

http://bbs.chinaunix.net/forum.php?mod=viewthread&tid=359433&page=1#pid2385375

https://stackoverflow.com/questions/7383803/writing-to-stdin-and-reading-from-stdout-unix-linux-c-programming

原文地址:https://www.cnblogs.com/any91/p/7072553.html