为什么管道的容量有限? [英] Why do pipes have a limited capacity?

查看:69
本文介绍了为什么管道的容量有限?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我听说管道需要有有限的容量.但我不明白为什么.如果进程无限制地写入管道会发生什么?

I've read that pipes need to have a limited capacity. But I don't understand why. What happens if a process writes into a pipe without a limit?

推荐答案

这是因为缓冲.管道不是神奇的",管道并不能确保所有进程都以锁步方式处理每个单独的字节或字符.相反,管道缓冲进程间输出,然后传递缓冲区.这个缓冲区大小限制就是你所指的.在许多 Linux 发行版和 macOS 中,缓冲区大小为 64KiB.

It's due to buffering. Pipes are not "magical", pipes do not ensure all processes process each individual byte or character in lockstep. Instead pipes buffer inter-process output and then pass the buffer along. And this buffer size limit is what you're referring to. In many Linux distros and in macOS the buffer size is 64KiB.

想象一下,有一个进程每秒向 stdout 输出 1GB 的数据——并且它通过管道传输到另一个进程,该进程每分钟只能在 stdin 上处理 100 字节的数据——考虑到那些千兆字节的数据必须去某个地方.如果有一个无限大小的缓冲区,那么你会很快填满拥有管道的任何操作系统组件的内存空间,然后开始分页到磁盘 - 然后你在磁盘上的页面文件会填满 - 这并不好.

Imagine there's a process that outputs 1GB of data every second to stdout - and it's piped to another process that can only process 100 bytes of data every minute on stdin - consider that those gigabytes of data have to go somewhere. If there was an infinitely sized buffer than you would quickly fill up the memory-space of whatever OS component owns the pipe and then start paging out to disk - and then your pagefile on disk would fill up - and that's not good.

通过设置最大缓冲区大小,输出进程将在缓冲区填满时得到通知,并且可以自由地处理该事件,但这是适当的(例如,如果它是随机数生成器,则暂停输出,如果它是网络监视器,则丢弃数据,通过崩溃等).

By having maximum buffer sizes, the output process will be notified when it's filled the buffer and it's free to handle that event however is appropriate (e.g. by pausing output if it's a random number generator, by dropping data if it's a network monitor, by crashing, etc).

这篇关于为什么管道的容量有限?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆