管道在 Linux 中是如何工作的? [英] How does a pipe work in Linux?

查看:36
本文介绍了管道在 Linux 中是如何工作的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

管道是如何工作的?如果我通过 CLI 运行一个程序并将输出重定向到一个文件,我是否能够在编写该文件时将该文件传输到另一个程序中?

How does piping work? If I run a program via CLI and redirect output to a file will I be able to pipe that file into another program as it is being written?

基本上,当一行写入文件时,我希望它立即通过管道传输到我的第二个应用程序(我正在尝试从现有程序中动态绘制图形).在继续下一个命令之前,不确定管道是否完成了第一个命令.

Basically when one line is written to the file I would like it to be piped immediately to my second application (I am trying to dynamically draw a graph off an existing program). Just unsure if piping completes the first command before moving on to the next command.

任何反馈将不胜感激!

推荐答案

如果你想将一个程序的输出重定向到另一个程序的输入,只需使用一个简单的管道:

If you want to redirect the output of one program into the input of another, just use a simple pipeline:

program1 arg arg | program2 arg arg

如果你想将 program1 的输出保存到一个文件中将它传送到 program2,你可以使用 tee(1):

If you want to save the output of program1 into a file and pipe it into program2, you can use tee(1):

program1 arg arg | tee output-file | program2 arg arg

管道中的所有程序同时运行.大多数程序通常使用阻塞 I/O:如果当它们尝试读取输入但什么都没有时,它们阻塞:也就是说,它们停止,并且操作系统- 安排它们运行,直到有更多输入可用(以避免占用 CPU).类似地,如果管道中较早的程序写入数据的速度比后面的程序读取数据的速度快,最终管道的缓冲区会填满并且写入器会阻塞:操作系统会取消调度它,直到管道的缓冲区被读取器清空,然后又可以继续写了.

All programs in a pipeline are run simultaneously. Most programs typically use blocking I/O: if when they try to read their input and nothing is there, they block: that is, they stop, and the operating system de-schedules them to run until more input becomes available (to avoid eating up the CPU). Similarly, if a program earlier in the pipeline is writing data faster than a later program can read it, eventually the pipe's buffer fills up and the writer blocks: the OS de-schedules it until the pipe's buffer gets emptied by the reader, and then it can continue writing again.

编辑

如果你想使用 program1 的输出作为命令行参数,你可以使用反引号或 $() 语法:

If you want to use the output of program1 as the command-line parameters, you can use the backquotes or the $() syntax:

# Runs "program1 arg", and uses the output as the command-line arguments for
# program2
program2 `program1 arg`

# Same as above
program2 $(program1 arg)

应该首选 $() 语法,因为它们更清晰,并且可以嵌套.

The $() syntax should be preferred, since they are clearer, and they can be nested.

这篇关于管道在 Linux 中是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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