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
: 轉換為無符號整型。
這些函數的用法類似,均用于內核中的字符串到數值的轉換。