bash 为什么我很少收到“cat: write error: Broken pipe”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49664991/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 16:52:53  来源:igfitidea点击:

Why am I getting "cat: write error: Broken pipe" rarely and not always

linuxbashgrepcatbroken-pipe

提问by Vishal-Lia

I am running some scripts with commands having catpipelined with greplike:

我运行一些脚本与具有命令cat与流水线grep一样:

cat file.txt | grep "pattern"

Most of the times there are no problems. But sometimes I get below error:

大多数时候没有问题。但有时我会收到以下错误:

cat: write error: Broken pipe

猫:写错误:管道损坏

So how do I find out when the command is causing this problem and why?

那么我如何找出命令何时导致此问题以及为什么?

回答by Inian

The reason is because the pipe is closed by grepwhen it still has some data to be read from cat. The signal SIGPIPEis caught by cat and it exits.

原因是管道grep在仍有一些数据要读取时关闭cat。信号SIGPIPE被 cat 捕获并退出。

What usually happens in a pipeline is the shell runs catin one process and grepin another. The stdout of catis connected to the write-end of the pipe and stdin of grepto the read end. What happened was grephit a pattern search that did not exist and exited immediately causing the read end of the pipe to be closed, which catdoes not like since it has some more data to be write out to the pipe. Since the write actions happens to an other which has been closed other end, SIGPIPEis caught by the caton which it immediately exits.

通常在管道中发生的是 shellcat在一个进程和grep另一个进程中运行。的标准输出cat连接到管道的写入端,标准输入连接到grep读取端。发生的事情是grep遇到了一个不存在的模式搜索并立即退出,导致管道的读取端关闭,这cat不喜欢,因为它有更多的数据要写到管道中。由于写入操作发生在另一端已关闭的其他对象上,因此会被立即退出的对象SIGPIPE捕获cat

For such a trivial case, you could remove the pipeline usage altogether and run it as grep "pattern" file.txtwhen the file's contents are made available over the stdin of grepon which it could read from.

对于这种微不足道的情况,您可以完全删除管道使用,并grep "pattern" file.txt在文件内容通过grep它可以读取的标准输入可用时运行它。

回答by ramzieus

You can use only grep without pipe like this :

您只能使用没有管道的 grep ,如下所示:

grep "pattern" file.txt

I think it's better to resolve this problem

我认为最好解决这个问题