linux - 'echo' 无限次调用 .write 函数

标签 linux command-line linux-kernel echo linux-device-driver

上下文

我编写了一个 Linux 设备驱动程序,其中实现了函数 readwrite。问题出在函数 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(从 Command LINE)时,它会写入 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

最佳答案

内核返回的值 .write函数解释为:

  • 错误代码,如果它小于零 (<0),

  • 写入的字节数,如果它大于或等于零 ( >=0 )

因此,为了告诉用户所有字节都已写入,.write函数应该返回它的 count参数。


如果是.write函数,返回零有一点意义:每个“标准”实用程序,如 echo只会调用write()再次发挥作用。

关于linux - 'echo' 无限次调用 .write 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48607992/

相关文章:

Java 命令行尖括号

Linux驱动开发: how to investigate copy_to_user() timing?

networking - linux内核中UDP包的路径

c++ - 如何在 C++ 中执行 SQLite 语句

python - Arduino Yun Python 脚本

python - 服务器端命令行排队

linux - 问题编译内核模块

c++ - 如何在 Linux 中优化构建

linux - 使得无法在文件夹内创建新文件

firefox - 从命令行选择 Firefox 中的选项卡