为什么可以将()写入STDIN? [英] Why is it possible to write() to STDIN?

查看:52
本文介绍了为什么可以将()写入STDIN?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

  int main(){char str [] ="Hello \ n";write(0,str,6);//将()写入STDIN返回0;} 

当我编译并执行该程序时,在终端中打印了 Hello .

为什么起作用? write()是否用 1 (STDOUT)替换了我的 0 (STDIN)参数?

解决方案

好,旧的Unix系统最初是用于串行终端的,并且有一个特殊的程序 getty 负责管理串行设备,打开并配置它们,在进入的连接上显示一条消息(中断信号),然后将打开的文件描述符传递给登录名,然后传递给Shell.

它曾经打开tty设备作为输入/输出来对其进行配置,然后将其复制到文件描述符0、1和2中.默认情况下,(仍然很旧) stty 命令默认情况下在标准输入上运行.为了确保兼容性,在现代Linux上,当您连接到终端时,仍然打开文件描述符0进行输入/输出.

它可以用作快速且肮脏的技巧,仅在将标准输入连接到终端时才显示提示,因为如果将标准输入重定向到只读文件或管道,则所有写操作都会失败(对过程),则不会打印任何内容.但这毕竟是一个肮脏的hack:试想一下,如果调用者将为输入/输出打开的文件作为标准输入传递给打开的文件,那会发生什么.这就是为什么良好做法建议对提示或消息使用stderr以避免它们在重定向流中丢失的原因将输出和输入保持在单独的流中,这不再困难,也不再需要.

TL/DR:如果连接到终端,则标准输入 会打开以进行输入/输出,即使名称和标准用法可能表明它是只读的.

I have the following code:

int main()
{
    char str[] = "Hello\n";
    write(0, str, 6);   // write() to STDIN
    return 0;
}

When I compiled and executed this program, Hello was printed in the terminal.

Why did it work? Did write() replace my 0 (STDIN) argument with 1 (STDOUT)?

解决方案

Well, old Unix systems were originaly used with serial terminals, and a special program getty was in charge to manage the serial devices, open and configure them, display a message on an incoming connexion (break signal), and pass the opened file descriptors to login and then the shell.

It used to open the tty device as input/output to configure it, and that was then duplicated in file descriptors 0, 1 and 2. And by default the (still good old) stty command operates by default on standard input. To ensure compatibility, on modern Linuxes, when you are connected to a terminal, file descriptor 0 is still opened for input/output.

It can be used as a quick and dirty hack to only display prompts when standard input is connected to a terminal, because if standard input is redirected to a read only file or pipe, all writes will fail (without any harm for the process) and nothing will be printed. But it is anyway a dirty hack: just imagine what happens if a caller passes a file opened for input/output as standard input... That's why good practices recommend to use stderr for prompts or messages to avoid having them lost in redirected stream while keeping output and input in separate streams, which is neither harder nor longer.

TL/DR: if you are connected to a terminal, standard input is opened for input/output even if the name and standard usage could suggest it is read only.

这篇关于为什么可以将()写入STDIN?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆