Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux綜合 >> Linux 核心

Linux 內核通用佇列 kfifo 使用筆記(讀《Linux 內核設計與實現》)

Linux 內核提供了通用佇列 Kfifo 的實作,位置在 kernel/kfifo.c。使用前需包含標頭檔 #include <linux/kfifo.h>。

1、建立佇列

動態建立:

int kfifo_alloc(struct kfifo *fifo, unsigned int size, gfp_t gfp_mask);

該函數會建立並初始化一個大小為 size 的 fifo,內核以 gfp_mask 標識分配佇列,成功回傳 0。範例:

struct kfifo fifo;
int ret;
// 建立一個大小為 PAGE_SIZE 的佇列,由內核分配記憶體
ret = kfifo_alloc(&fifo, PAGE_SIZE, GFP_KERNEL);
if (ret)
    return ret;

若自行分配緩衝,可呼叫:

void kfifo_init(struct kfifo *kfifo, void *buffer, unsigned int size);

它會建立並初始化一個 kfifo 對象,使用由 buffer 指向的 size 位元組記憶體。以上兩個函數的 size 必須是 2 的冪。靜態宣告可用 DECLARE_KFIFO(name, size); 與 INIT_KFIFO(name);。

2、堆入佇列資料

unsigned int kfifo_in(struct kfifo *fifo, const void *from, unsigned int len);

把 from 指標所指的 len 位元組資料拷貝到 fifo 佇列中,成功回傳實際寫入的位元組數。

3、摘取佇列資料

unsigned int kfifo_out_peek(struct kfifo *fifo, void *to, unsigned int len, unsigned offset);

與 kfifo_out 類似,offset 為 0 時讀取佇列頭,offset 指向佇列中的索引位置。

4、取得佇列長度

// 回傳 kfifo 佇列空間的總大小
static inline unsigned int kfifo_size(struct kfifo *fifo);
// 回傳佇列中已堆入資料的大小
static inline unsigned int kfifo_len(struct kfifo *fifo);
// 取得還有多少可用空間
static inline unsigned int kfifo_avail(struct kfifo *fifo);
// 判斷是否為空,非 0 為空
static inline int kfifo_is_empty(struct kfifo *fifo);
// 判斷是否為滿,非 0 為滿
static inline int kfifo_is_full(struct kfifo *fifo);

5、重置與撤銷佇列

// 拋棄佇列中所有內容
static inline void kfifo_reset(struct kfifo *fifo);
// 撤銷以 kfifo_alloc() 分配的佇列
void kfifo_free(struct kfifo *fifo);

使用範例

unsigned int i;
// 將 0~31 壓入名為 fifo 的 kfifo 中
for (i = 0; i < 32; i++)
    kfifo_in(fifo, &i, sizeof(i));

unsigned int val;
int ret;
ret = kfifo_out_peek(fifo, &val, sizeof(val), 0);
if (ret != sizeof(val))
    return -EINVAL;
printk(KERN_INFO "%u\n", val);   // 應輸出 0

// 摘取並打印 kfifo 中的所有元素
while (kfifo_avail(fifo)) {
    ret = kfifo_out(fifo, &val, sizeof(val));
    if (ret != sizeof(val))
        return -EINVAL;
    printk(KERN_INFO "%u\n", val);   // 依序印出 0 到 31
}
Copyright © Linux教程網 All Rights Reserved