0
点赞
收藏
分享

微信扫一扫

circ_buf


​​struct circ_buf: Circular Buffers in the Linux Kernel - Daniel Berliner (danberliner.com)​​

前期资料收集

对buf大小有要求:

All of the macros have a parameter called size, which is not part of the struct. Size is the allocated length of buf which must be a power of 2. 必须是2的指数

#include <stdio.h>
#define CIRC_SPACE_TO_END(head,tail,size) \
({int end = (size) - 1 - (head); \
int n = (end + (tail)) & ((size)-1); \
n <= end ? n : end+1;})

/* Return count in buffer. */
#define CIRC_CNT(head,tail,size) (((head) - (tail)) & ((size)-1))

/* Return space available, 0..size-1. We always leave one free char
as a completely full buffer has head == tail, which is the same as
empty. */
#define CIRC_SPACE(head,tail,size) CIRC_CNT((tail),((head)+1),(size))
int main()
{
/* Write C code in this online editor and run it. */
printf("Hello, World! \n");
int i=0;
int j=0,m=0;
int end;


end= CIRC_SPACE_TO_END(80,30,128); //head 比tail 大。 head到buffer尾部为可以写入的。此外 0~tail也是可以写入的空间。

printf("end: %d\n",end );

end= CIRC_SPACE_TO_END(30,70,128); //head 比tail 小。head到tail中间的为此次可以写入的空间。
int count;
count = CIRC_CNT(30,60,128);
printf("end: %d count:%d\n",end,count );

return 0;
}

Hello, World!   以下为程序输出,和预期一致。即此次到buf尾部有多少可写的空间。
end: 48
end: 39  count:98

但是在第一种情况,即head比tail大的情况时, 到buf尾部可能只有 1两个字节,而从0-tail间有大量的空间可以使用。

用户在第一次调用写buf接口时,首先将此 1-2个字节写满;而后第二次调用时,此时head已经跑到0的位置,则可以看到0(即此时的head)-tail之间的大量可用空间了。

举报

相关推荐

0 条评论