我正在编写一个可加载的内核模块,并且需要使用qsort()函数,该函数显然无法在内核空间中使用。

我可以使用具有类似功能的功能吗?

(内核版本3.5.0)

最佳答案

linux内核包括执行heapsort的功能,该实现的功能与quicksort相似。内核开发人员建议堆排序优于快速排序(在内核内部),并给出以下理由:



header

#include <linux/sort.h>

原型(prototype)
void sort(
    void *base, size_t num, size_t size,
    int (*cmp_func)(const void *, const void *),
    void (*swap_func)(void *, void *, int size));

用法
static int compare(const void *lhs, const void *rhs) {
    int lhs_integer = *(const int *)(lhs);
    int rhs_integer = *(const int *)(rhs);

    if (lhs_integer < rhs_integer) return -1;
    if (lhs_integer > rhs_integer) return 1;
    return 0;
}

void example() {
    int values[1024] = {...};
    sort(values, 1024, sizeof(int), &compare, NULL);
}

关于c - 在内核空间中是否有类似于qsort()的函数?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17175295/

10-11 23:09
查看更多