sysfs 中的 kstrtoint for c 内核模块

kstrtoint in sysfs for c kernel module

您好,我正在尝试使用 kobject 从 sysfs 写入一个 int 数组。所以输入是一个 char* 和一个大小变量。然而,我似乎无法让它发挥作用。我的预期输入是 "num1 num2 num3 "

static ssize_t pids_store(struct kobject *kobj, struct kobj_attribute *attr, const char *buf, size_t count) {

int num_count = 0;
int i = 0;
int result = 0;
int cur_pid = 0;
char *dst;
char *ddst;

printk(KERN_INFO "GPIO_DEGUG: enter");

dst = buf;
ddst = buf;

printk(KERN_INFO "GPIO_DEGUG:  size of buffer %d ",count);


while(ddst < (buf + sizeof(size_t)*count)) {
ddst ++;
if (ddst[0] == ' ') {
   result = kstrtoint(dst,10,&cur_pid);
   dst=ddst+1;

   printk(KERN_INFO "GPIO_DEGUG: kstrtoint suceeded %d ",cur_pid);
   printk(KERN_INFO "GPIO_DEGUG: kstrtoint suceeded res: %d ",result);
   pids[num_count] = cur_pid;
   num_count += 1;
   }
}

for(i=0;i<num_count;i++) {
    printk(KERN_INFO "GPIO_TEST: pid: %d \n", pids[i]);
}
printk(KERN_INFO "GPIO_DEBUG: leaving\n");
return count;                                         
}

当我echo "100 " > /sys/vt/vt7/pids我得到

[ 2765.712770] GPIO_DEGUG: enter 
[ 2765.724468] GPIO_DEGUG:  size of buffer 5 
[ 2765.735101] GPIO_DEGUG: kstrtoint suceeded 0 
[ 2765.746526] GPIO_DEGUG: kstrtoint suceeded res: -22 
[ 2765.757746] GPIO_DEBUG: leaving 

我想这是一个参数错误,如果有帮助就好了,谢谢。

这里定义了 kstrtoint 函数:

http://lxr.free-electrons.com/source/lib/kstrtox.c#L245

如果您注意到函数中定义的 *res 的最后一个值就是您希望使用的值。在您的情况下, cur_pid 应该是您要打印的值,如果成功,结果应始终为零。我建议检查结果以确保转换成功。

这应该有效:

int cur_pid, result;
char *dst = NULL;

cur_pid = result = 0;
dst = buf;

result = kstrtoint(dst, 10, &cur_pid);
if (result)
     printk(KERN_INFO "GPIO_DEGUG: kstrtoint suceeded res: %d ", cur_pid);
else
     printk(KERN_INFO "ERROR");

函数 kstrtoint 需要完整的字符串包含 单个整数值 。唯一的例外是字符串末尾的换行符:

The string must be null-terminated, and may also include a single newline before its terminating null.

如您所见,字符串“100”不符合该要求:它包含超过 space.

为了仅将字符串的一部分解析为整数,您可以使用 simple_strtol:

long val = simple_strtol(dst, &ddst, 10);
if(ddst == ddst) {/* Parsing has been failed. */};

虽然这个函数被标记为已过时,但内核中仍有一些代码在使用它。

另一种可能性是使用sscanf。它期望字符串中有固定数量的整数,但这是属性的常见情况:不推荐具有复杂的属性表示

The conventions for sysfs state that each attribute should contain a single, human-readable value; if you have a lot of information to return, you may want to consider splitting it into multiple attributes.

(Linux Device Drivers 3, chapter 14).