除了读取直到没有剩余内容之外,还有其他方法可以到达管道的最后位置吗?
目前的方式:
while(read(pipe, input, sizeof(input))>0);
有没有更好的寻求方式?
Current way:
while(read(pipe, input, sizeof(input))>0);
Is there a better one with seeking?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
计算机上的管道就像“现实”世界中的管道一样......数据从一端流向另一端,一旦从管道中消失,就无法恢复。就像真实的管道一样,不知道水流何时会停止,因此在水流实际结束之前尝试找到水流的终点是没有意义的。
Pipes on computers are like pipes in the "real" world... Data flows from one end to the other, and once it's gone from the pipe there is no getting it back. And like a real pipe there is no knowing when the flow will stop, so there is no meaning to try and find the end of the flow before it actually ends.
不,你不能在管道中寻找。你必须通读它。
您的代码应该处理 read 返回 -1 的情况,而不仅仅是假设循环结束时它已正确定位。
No, you can't seek in pipes. You'll have to read through it.
Your code should handle cases where read returns -1 though, and not just assume it's properly positioned when the loop ends.
您可以将 splice( 2 ) 插入 /dev/null 来使用所有数据,但很难说这是“更好”。
You can splice( 2 ) into /dev/null to consume all of the data, but it's a tough argument that this is "better".
您还可以过早关闭管道的可读端。但如果编写器端代码不处理这种情况(例如在写入之前调用
poll
或select
),它将收到一个SIGPIPE
信号。You also could close the readable end of the pipe prematurely. But if the writer end code don't handle that case (by e.g. calling
poll
orselect
before writing), it will get aSIGPIPE
signal.