How in portable C to seek forward when reading from a pipe

三世轮回 提交于 2019-12-10 03:16:57

问题


Since fseek() does not work on pipes what methods exist for simulating seeking forward? The naive approach is to use fread() and throw away the contents read into the memory buffer. For huge seeks to avoid huge buffers you would use the same buffer over and over with the final read using just a part of the buffer.

But is this the only approach? Is there another way which avoids the buffer and the potential multiple read?


回答1:


Yes, it is the only way. I would use a buffer somewhere around 1k-8k. With much smaller the syscall overhead for read will come into play, and with much larger you'll evict useful data from the cache.




回答2:


Seeking doesn't make sense on pipes because the input is produced dynamically (not stored on disk). The lseek kernel system call is not implemented for pipes.

Also have in mind that a pipe is essentially a producer-consumer buffer of a limited, fixed size. When it gets full, the producer is suspended until the consumer reads the oldest data.



来源:https://stackoverflow.com/questions/5806522/how-in-portable-c-to-seek-forward-when-reading-from-a-pipe

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