且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

cURL 为什么会返回错误“(23) 写入正文失败"?

更新时间:2023-02-19 22:27:36

这种情况发生在管道程序(例如 grep)在前一个程序完成写入整个页面之前关闭读取管道.

This happens when a piped program (e.g. grep) closes the read pipe before the previous program is finished writing the whole page.

curl "url" |grep -qs foo,一旦 grep 有了它想要的东西,它就会关闭 curl 的读取流.cURL 没有预料到这一点,并发出写入正文失败"错误.

In curl "url" | grep -qs foo, as soon as grep has what it wants it will close the read stream from curl. cURL doesn't expect this and emits the "Failed writing body" error.

一种解决方法是通过一个中间程序管道传输流,该程序总是在将其提供给下一个程序之前读取整个页面.

A workaround is to pipe the stream through an intermediary program that always reads the whole page before feeding it to the next program.

例如

curl "url" | tac | tac | grep -qs foo

tac 是一个简单的 Unix 程序,它读取整个输入页面并反转行序(因此我们运行它两次).因为它必须读取整个输入才能找到最后一行,所以在 cURL 完成之前它不会向 grep 输出任何内容.Grep 仍然会在它找到要查找的内容时关闭读取流,但它只会影响 tac,它不会发出错误.

tac is a simple Unix program that reads the entire input page and reverses the line order (hence we run it twice). Because it has to read the whole input to find the last line, it will not output anything to grep until cURL is finished. Grep will still close the read stream when it has what it's looking for, but it will only affect tac, which doesn't emit an error.