Linux中的管道会丢失数据吗? [英] Can a pipe in Linux ever lose data?

查看:390
本文介绍了Linux中的管道会丢失数据吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

它可以包含多少数据有上限?

And is there an upper limit on how much data it can contain?

推荐答案

除非机器崩溃,否则它不会丢失数据.很容易滥用它,并认为您正在丢失数据,要么是因为写入操作未能写入您请求的所有数据,而您没有检查返回值,要么是读取操作出了点问题.

Barring a machine crash, no it can't lose data. It's easy to misuse it and think you're losing data however, either because a write failed to write all the data you requested and you didn't check the return value or you did something wrong with the read.

它可以保存的最大数据量取决于系统-如果您尝试写更多数据,则可能会写短或者写程序将阻塞直到有可用空间为止. pipe(7)手册页包含许多有关管道的有用信息,包括(至少在Linux上)缓冲区的大小. Linux根据版本而有4K或64K的缓冲区.

The maximum amount of data it can hold is system dependent -- if you try to write more than that, you'll either get a short write or the writer will block until space is available. The pipe(7) man page contains lots of useful info about pipes, including (on Linux at least) how big the buffer is. Linux has buffers of 4K or 64K depending on version.

修改

Tim提到了SIGPIPE,这也是一个似乎会丢失数据的潜在问题.如果读取器在读取管道中的所有内容之前先将其关闭,则未读数据将被丢弃,并且写入者在写入更多内容或关闭管道时将获得SIGPIPE信号,表明已发生这种情况.如果他们阻止或忽略SIGPIPE,他们将收到EPIPE错误.这涵盖了保罗提到的情况.

Tim mentions SIGPIPE, which is also a potential issue that can seem to lose data. If the reader closes the pipe before reading everything in it, the unread data will be thrown away and the writer will get a SIGPIPE signal when they write more or close the pipe, indicating that this has occurred. If they block or ignore the SIGPIPE, they'll get an EPIPE error. This covers the situation Paul mentioned.

PIPE_BUF是一个常量,它告诉您 atomic 写入缓冲区的限制.此大小或更小的任何写入将完全成功或阻塞,直到完全成功为止(如果管道处于非阻塞模式,则给出EWOULDBLOCK/EAGAIN).它与内核的管道缓冲区的实际大小无关,尽管显然缓冲区必须至少为PIPE_BUF大小才能满足原子性保证.

PIPE_BUF is a constant that tells you the limit of atomic writes to the buffer. Any write this size or smaller will either succeed completely or block until it can succeed completely (or give EWOULDBLOCK/EAGAIN if the pipe is in non-blocking mode). It has no relation to the actual size of the kernel's pipe buffer, though obviously the buffer must be at least PIPE_BUF in size to meet the atomicity guarentee.

这篇关于Linux中的管道会丢失数据吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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