简体   繁体   English

为什么重定向到stdout和stdin在PIPE编程中如此常见

[英]Why redirection to stdout and stdin so common in PIPE programming

I am very much new to IPC programming in C. I had a very basic question, why many of our C codes use dup2 to make stdout as write head and stdin as read head for the PIPE. 我对使用C进行IPC编程非常陌生。我有一个非常基本的问题,为什么我们的许多C代码都使用dup2将stdout用作PIPE的写头,将stdin用作PIPE的读头。 Is there any benefit, comapred to an array of integer type and using the array as an input to pipe call? 共映射到整数类型的数组并将该数组用作管道调用的输入有什么好处?

Many C programs are written as filters, which (by default) read from standard input and write to standard output. 许多C程序被编写为过滤器,(默认情况下)从标准输入读取并写入标准输出。 The plumbing with pipes exploits, and supports, idioms of sending the output from one program to the input of another, as with: 使用管道的管道利用并支持从一个程序向另一个程序的输入发送输出的惯用法,例如:

ls | wc -l

That's why you very often end up with code connecting the pipe file descriptors to standard input or standard output. 这就是为什么您经常会得到将管道文件描述符连接到标准输入或标准输出的代码的原因。 If you needed to make programs read from, or write to, arbitrary file descriptors, you'd have to supply control arguments to tell them what to do. 如果需要使程序能够读取或写入任意文件描述符,则必须提供控制参数来告诉它们该怎么做。 Granted, these days on systems such as Linux with the /dev/fd file system, it would be doable, but that's a recent innovation that was not available when many programs were first written. 可以肯定的是,如今在具有/dev/fd文件系统的Linux之类的系统上,它是可行的,但这是最近的创新,当第一次编写许多程序时,这种创新是不可用的。 You could get nearly the same result as above using: 您可以使用以下方法获得与上述几乎相同的结果:

ls | wc -l /dev/fd/0

but wc would echo the file name in this case, whereas it does not echo the file name when no name is given as in the first example. 但是在这种情况下, wc会回显文件名,而在第一个示例中没有给出名称时,它不会回显文件名。

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

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