我写了一个Linux设备驱动程序,其中实现了函数read
和write
。问题在于函数write,这里是代码的一部分:
ssize_t LED_01_write(struct file *filp, const char __user *buf, size_t count, loff_t *f_pos)
{
int retval = 0;
PDEBUG(" reading from user space -> wrinting in kernel space\n");
//struct hello_dev *dev = filp->private_data;
if (count > COMMAND_MAX_LENGHT){
printk(KERN_WARNING "[LEO] LED_01: trying to write more than possible. Aborting write\n");
retval = -EFBIG;
goto out;
}
if (down_interruptible(&(LED_01_devices->sem_LED_01))){
printk(KERN_WARNING "[LEO] LED_01: Device was busy. Operation aborted\n");
return -ERESTARTSYS;
}
if (copy_from_user((void*)&(LED_01_devices-> LED_value), buf, count)) {
printk(KERN_WARNING "[LEO] LED_01: can't use copy_from_user. \n");
retval = -EPERM;
goto out_and_Vsem;
}
write_status_to_LED();
PDEBUG(" Value instert: %u \n", LED_01_devices-> LED_value);
out_and_Vsem:
write_times++;
up(&(LED_01_devices->sem_LED_01));
out:
return retval;
}
如果我在C编译程序中使用该模块,它正常工作,正如预期的那样。
当我执行echo -n 1 > /dev/LED_01
(来自命令行)时,它会写入INFINITE次,即使使用Ctrl + C也不会停止。我需要重启。
这里是正常工作的测试函数的剪切代码:
// ON
result = write(fd, (void*) ON_VALUE, 1);
if ( result != 0 ){
printf("Oh dear, something went wrong with write()! %s\n", strerror(errno));
}
else{
printf("write operation executed succesfully (%u)\n",ON_VALUE[0]);
}
驱动程序中的问题或我使用echo
的方式?
如果您需要完整的源代码,则使用的所有文件都存储in this git repository folder
答案 0 :(得分:1)
内核的.write
函数返回的值被解释为:
错误代码,如果小于零(<0
),
写入的字节数,如果大于或等于零(>=0
)
因此,为了告诉用户所有字节都已写入,.write
函数应返回其count
参数。
如果是.write
函数,则返回零有一点意义:echo
之类的每个“标准”实用程序都会再次调用write()
函数。