什么是管道
- 管道 | pipes 最早最清晰的陈述来源于
McIlroy
由1964
年写的一份内部文件.这份文件提出像花园的水管那样把程序连接在一起.文档全文内容如下:
Summary--what's most important.
To put my strongest concerns into a nutshell:
1. We should have some ways of coupling programs like
garden hose--screw in another segment when it becomes when
it becomes necessary to massage data in another way.
This is the way of IO also.
2. Our loader should be able to do link-loading and
controlled establishment.
3. Our library filing scheme should allow for rather
general indexing, responsibility, generations, data path
switching.
4. It should be possible to get private system components
(all routines are system components) for buggering around with.
M. D. McIlroy
October 11, 1964
Unix
的缔造者肯.汤普森
只花了一个小时就在操作系统中实现了管道的系统调用.他自己说这是简直小菜一碟,因为I/O的重定向机制是管道的实现基础,但效果确是很震撼.管道的本质是I/O
的重定向,是对数据的不断编辑,不断流动,只有这样的数据才有价值.- 在文件概念篇中提到过,
Unix
"一切皆文件"的说法是源于输入输出的共性,只要涵盖这两个特性都可以也应当被抽象成文件统一管理和流动. 拿跟城市的发展来举例,越是人口流动和资金流动频繁的城市一定是越发达的城市.这个道理请仔细品,城市的规划应该让流动的成本变低,时间变短,而不是到处查身份证,查户口本.对内核设计者来说也是一样,能让数据流动的成本变得极为简单,方便的系统也一定是好的架构,Unix
能做到多年强盛不衰其中一个重要原因是它仅用一个|
符号实现了文件之间的流动性问题.这是一种伟大的创举,必须用专门的章篇对其大书特书.
管道符号 |
管道符号是两个命令之间的一道竖杠 |
,简单而优雅,例如,ls
用于显示某个目录中文件,wc
用于统计行数.
ls | wc
则代表统计某个目录下的文件数量
再看个复杂的:
$ < colors.txt sort | uniq -c | sort -r | head -3 > favcolors.txt
colors.txt
为原始的文件内容,输出给sort
处理sort
对colors.txt
内容进行顺序编辑后输出给uniq
处理uniq
对 内容进行去重编辑后输出给sort -r
处理sort -r
对内容进行倒序编辑后输出给head -3
处理head -3
对 内容进行取前三编辑后输出到favcolors.txt
文件保存.- 最后
cat favcolors.txt
查看结果
$ cat favcolors.txt
4 red
3 blue
2 green
经典管道案例
以下是linux
官方对管道的经典案例. 查看 pipe
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#