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

查看:70
本文介绍了管道在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中,则可以使用

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

管道中的所有程序都同时运行.大多数程序通常使用 blocking I/O:如果尝试读取其输入而没有任何输入,则会对其进行 block :即,它们停止了,并且操作系统-安排它们运行直到有更多输入可用(以避免耗尽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天全站免登陆