kstrtoul 函数概述
kstrtoul
是 Linux 内核中的一个函数,用于将字符串转换为无符号长整型(unsigned long
)。该函数定义在 <linux/kernel.h>
头文件中,常用于内核模块中解析用户空间传递的字符串参数。
函数原型
int kstrtoul(const char *s, unsigned int base, unsigned long *res);
s
: 待转换的字符串。base
: 转换的进制基数(0 表示自动检测,支持 2~36 进制)。res
: 转换结果存储的指针。
返回值
- 成功时返回
0
。 - 失败时返回错误码(如
-EINVAL
表示无效参数,-ERANGE
表示数值超出范围)。
使用示例
以下是一个简单的示例,展示如何在内核模块中使用 kstrtoul
:
#include <linux/kernel.h>
#include <linux/module.h>static int __init example_init(void) {const char *str = "12345";unsigned long value;int ret;ret = kstrtoul(str, 10, &value);if (ret < 0) {printk(KERN_ERR "Failed to convert string to unsigned long\n");return ret;}printk(KERN_INFO "Converted value: %lu\n", value);return 0;
}static void __exit example_exit(void) {printk(KERN_INFO "Module unloaded\n");
}module_init(example_init);
module_exit(example_exit);
MODULE_LICENSE("GPL");
注意事项
- 字符串格式: 字符串必须符合无符号长整型的格式要求,否则会返回
-EINVAL
。 - 进制基数: 若
base
为 0,函数会自动检测字符串的进制(如0x
前缀为 16 进制,0
前缀为 8 进制)。 - 范围检查: 转换后的值必须在
unsigned long
的范围内,否则返回-ERANGE
。 - 内核上下文: 该函数仅在内核空间使用,不可用于用户空间程序。
相关函数
kstrtol
: 转换为有符号长整型。kstrtoull
: 转换为无符号长长整型。kstrtouint
: 转换为无符号整型。
这些函数的用法类似,均用于内核中的字符串到数值的转换。