[英]Linux Kernel Module : Problem with kernel_write function
I have a problem using kernel_write
function while I am developing LKM for Linux 4.14.73 version.我在为 Linux 4.14.73 版本开发 LKM 时使用
kernel_write
函数时遇到问题。
This is the part of my module where I am facing the issue:这是我面临问题的模块的一部分:
void change_led_state(char *led_path, int led_value)
{
printk("we are in change_led_state\n");
size_t len = sizeof(led_value);
char lpath[64];
ssize_t rk=0;
strncpy(lpath, led_path, sizeof(lpath) - 1);
lpath[sizeof(lpath) - 1] = '\0';
f_led = filp_open(lpath, O_WRONLY , 0);
if (f_led == NULL) {
printk("Unable to access led\n");
return;
}
rk = kernel_write(f_led, led_value, len, &f_led->f_pos);
printk("rk = %d\n", rk);
filp_close(f_led, NULL);
}
rk is usually getting a negative value. rk通常为负值。 I think it must be positive.
我想应该是积极的。 What's wrong with the function please?
请问这个功能有什么问题吗? How can I correct it?
我该如何纠正它?
For more informations, I have the same code but in user-space program, and it's working fine, I just want to replace it to kernel space.有关更多信息,我有相同的代码,但在用户空间程序中,并且工作正常,我只想将其替换为内核空间。 This is the user space program:
这是用户空间程序:
void change_led_state(char *led_path, int led_value)
{
char lpath[64];
FILE *led_fd;
strncpy(lpath, led_path, sizeof(lpath) - 1);
lpath[sizeof(lpath) - 1] = '\0';
led_fd = fopen(lpath, "w");
if (led_fd == NULL) {
fprintf(stderr, "simplekey: unable to access led\n");
return;
}
fprintf(led_fd, "%d\n", led_value);
fclose(led_fd);
}
void reset_leds(void)
{
change_led_state(LED_PATH "/" green "/brightness", 0);
}
void eval_keycode(int code)
{
static int green_state = 0;
switch (code) {
case 260:
printf("BTN pressed\n");
// figure out red state
green_state = green_state ? 0 : 1;
change_led_state(LED_PATH "/" green "/brightness", green_state);
break;
default :
printf("Wrong Button was pressed\n");
break;
}
}
In the main fuction I just call eval_keycode function and it's working.在主要功能中,我只是调用 eval_keycode 功能,它正在工作。 What mistakes I have made?
我犯了什么错误?
In your call:在你的电话中:
rk = kernel_write(f_led, led_value, len, &f_led->f_pos);
The second parameter is supposed to be a char *
, but you are passing an int
.第二个参数应该是一个
char *
,但你传递的是一个int
。
In addition, when writing to the "/sys/class/leds/[device]/brightness" file, the code that handles this expects a pointer to a string of decimal digits, terminated by some non-digit character (such as a newline) or a null terminator.此外,当写入“/sys/class/leds/[device]/brightness”文件时,处理这个的代码需要一个指向十进制数字字符串的指针,由一些非数字字符(例如换行符)终止) 或空终止符。
You need to "print" your led_value
to a char
array as a decimal number and write the array contents to the file:您需要将
led_value
作为十进制数“打印”到char
数组,并将数组内容写入文件:
char led_valstr[20]; /* should be large enough */
len = scnprintf(led_valstr, sizeof(led_valstr), "%d\n", led_value);
rk = kernel_write(f_led, led_valstr, len, &f_led->f_pos);
(EDIT: corrected call to scnprintf
.) (编辑:更正了对
scnprintf
的调用。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.