linux termios 之 VMIN VTIME

在Linux串口编程中,VMIN和VTIME是控制read阻塞行为的关键参数。VMIN优先确保至少读取指定字节数,而VTIME则涉及超时设置。当两者皆不为0时,read会先等待接收到第一个字节,如果在VTIME时间内未接收完整字节数,则返回已接收的字节;若一直没有接收任何字节,read将保持阻塞状态。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在linux串口编程的时候,灵活应用VMIN VTIME会给程序数据处理提供更大的便利性。

VMIN VTIME是linux串口配置参数里面的两项控制read的参数,该参数只有在阻塞读的情况下才会有效。

The MIN and TIME are stored in elements of the c_cc array, which is a member of
the struct termios structure. Each element of this array has a particular role, and each
element has a symbolic constant that stands for the index of that element. VMIN and VMAX
are the names for the indices in the array of the MIN and TIME slots.

The MIN and TIME values interact to determine the criterion for when read should
return; their precise meanings depend on which of them are nonzero. There are four possible
cases:
 Both TIME and MIN are nonzero.
In this case, TIME specifies how long to wait after each input character to see if more
input arrives. After the first character received, read keeps waiting until either MIN
bytes have arrived in all, or TIME elapses with no further input.
read always blocks until the first character arrives, even if TIME elapses first. read
can return more than MIN characters if more than MIN happen to be in the queue.
 Both MIN and TIME are zero.
In this case, read always returns immediately with as many characters as are available
in the queue, up to the number requested. If no input is immediately available, read
returns a value of zero.
 MIN is zero but TIME has a nonzero value.
In this case, read waits for time TIME for input to become available; the availability
of a single byte is enough to satisfy the read request and cause read to return. When
it returns, it returns as many characters as are available, up to the number requested.
If no input is available before the timer expires, read returns a value of zero.
 TIME is zero but MIN has a nonzero value.
In this case, read waits until at least MIN bytes are available in the queue. At that
time, read returns as many characters as are available, up to the number requested.
read can return more than MIN characters if more than MIN happen to be in the
queue.

官方的介绍就是这样,VMIN VTIME配置不同的值的时候read的效果会不一样。

从上面的4种情况的解释可以发现:

1.优先满足VMIN,即这两项参数设计的目的就是尽量保证读取字节数,在VMIN无法完全满足的情况下,才会使用VTIME处理

2.为0则表示不考虑。即VMIN为0,表示不考虑字节数,VTIME为0,表示不考虑超时

基于以上2条就不难理解VMIN VTIME都不为0的情况了:

read一直等待知道接到第一个字节,若超过VTIME时间还未接到字节,则返回接到的字节,若一直未接到字节,则read不会返回。

这一条说明了VMIN优先的原则,没有接到字节read是不会因为VTIME而超时返回的。就是因为这一点理解错误,导致之前项目中一直纳闷程序怎么会一直卡在read不返回。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值