linux termios 之 VMIN VTIME

来源:互联网 发布:中小型网络解决方案 编辑:程序博客网 时间:2024/04/29 01:43

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

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

The MIN and TIME are stored in elements of the c_cc array, which is a member ofthe struct termios structure. Each element of this array has a particular role, and eachelement has a symbolic constant that stands for the index of that element. VMIN and VMAXare 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 shouldreturn; their precise meanings depend on which of them are nonzero. There are four possiblecases: Both TIME and MIN are nonzero.In this case, TIME specifies how long to wait after each input character to see if moreinput arrives. After the first character received, read keeps waiting until either MINbytes have arrived in all, or TIME elapses with no further input.read always blocks until the first character arrives, even if TIME elapses first. readcan 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 availablein the queue, up to the number requested. If no input is immediately available, readreturns 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 availabilityof a single byte is enough to satisfy the read request and cause read to return. Whenit 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 thattime, 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 thequeue.

官方的介绍就是这样,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不返回。

0 0