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
Why am I getting "cat: write error: Broken pipe" rarely and not always
提问by Vishal-Lia
I am running some scripts with commands having cat
pipelined with grep
like:
我运行一些脚本与具有命令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 grep
when it still has some data to be read from cat
. The signal SIGPIPE
is caught by cat and it exits.
原因是管道grep
在仍有一些数据要读取时关闭cat
。信号SIGPIPE
被 cat 捕获并退出。
What usually happens in a pipeline is the shell runs cat
in one process and grep
in another. The stdout of cat
is connected to the write-end of the pipe and stdin of grep
to the read end. What happened was grep
hit a pattern search that did not exist and exited immediately causing the read end of the pipe to be closed, which cat
does 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, SIGPIPE
is caught by the cat
on 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.txt
when the file's contents are made available over the stdin of grep
on 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
我认为最好解决这个问题