Linux管道(Pipe)是Unix/Linux系统中一种强大的进程间通信(IPC)机制,它允许将一个进程的输出直接作为另一个进程的输入。管道使用竖线符号|
表示,是命令行操作中最重要的特性之一。
匿名管道(Anonymous Pipe)
实现机制
# 基本语法
command1 | command2 | command3 ...
# 示例
cat access.log | grep "404" | sort | uniq -c | sort -nr
#include <unistd.h>
#include <stdio.h>
int main() {
int fd[2];
pid_t pid;
// 创建管道
if (pipe(fd) == -1) {
perror("pipe");
return 1;
}
pid = fork();
if (pid == 0) { // 子进程
close(fd[0]); // 关闭读端
dup2(fd[1], STDOUT_FILENO); // 将标准输出重定向到管道写端
execlp("ls", "ls", "-l", NULL);
} else { // 父进程
close(fd[1]); // 关闭写端
dup2(fd[0], STDIN_FILENO); // 将标准输入重定向到管道读端
execlp("wc", "wc", "-l", NULL);
}
return 0;
}
数据处理流水线
# 统计日志中不同状态码出现的次数
cat web.log | awk '{print $9}' | sort | uniq -c | sort -nr
实时监控
# 监控系统日志中的错误信息
tail -f /var/log/syslog | grep -i "error"
复杂命令组合
# 查找并压缩特定文件
find . -name "*.log" -type f -mtime +30 | xargs gzip
数据转换
# 将CSV转换为JSON
cat data.csv | csvtojson > data.json
管道的限制
替代方案
bash
mkfifo mypipe
cat mypipe & # 读取端
echo "data" > mypipe # 写入端
bash
command > file # 输出重定向
command < file # 输入重定向
bash
diff <(ls dir1) <(ls dir2)
多级管道
ps aux | grep httpd | awk '{print $2}' | xargs kill
tee命令分流
command1 | tee file.txt | command2
处理二进制数据
dd if=/dev/sda | gzip > disk.img.gz
避免管道错误
set -o pipefail # 管道中任一命令失败则整个管道失败
并行处理
cat bigfile | parallel --pipe -N1000 process_chunk
缓冲区大小
fcntl()
系统调用查询和修改(某些系统)性能优化
awk
替代多个grep
+cut
组合)内存使用
pv
命令监控数据流
bash
dd if=/dev/zero | pv | dd of=/dev/null
管道是Linux/Unix哲学"小工具,组合使用"的核心体现,掌握管道技术可以极大提高命令行操作的效率和灵活性。