Piping to head results in broken pipe in shell script called from python

我的未来我决定 提交于 2019-12-01 18:22:30

If one of the parent processes traps sigpipe, then the pipeline will inherit the ignore signal disposition, which will cause this problem you're experiencing.

This can be (safely) reproduced with:

( trap '' pipe; var=`< /dev/urandom tr -dc _A-Z-a-z-0-9 | head -c8 )

Normally, the head -c8 command will be done pretty soon at which point its stdin is closed. Since it's stdin is a pipe connected to the stdout of tr, it now no longer makes sense for tr to write to its stdout. Once it tries to, the system will kill it with SIGPIPE. Unless tr ignores this signal or has inherited the ignore (SIG_IGN) disposition for this signal from its parent. Then a write to tr's broken stdout will simply cause a regular error and set errno to EPIPE at which point tr will most likely stringify and outputs this error to its stderr and exit.

Christian Long

This answer provides a good summary of the problem with piping from Python to head, and shows some workarounds.

https://stackoverflow.com/a/30091579/456550

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!