【问题标题】:Writing to Linux device driver causes infinite loop写入 Linux 设备驱动程序导致无限循环
【发布时间】:2018-05-02 08:08:36
【问题描述】:

我一直在编写一个可以从用户空间读取和写入的内核空间设备驱动程序。打开、读取、释放操作都可以完美运行。我遇到的问题是应该访问设备驱动程序并向其写入内容的用户空间代码。

用户空间程序写入两个文件:1) 到 .txt 文件(并在控制台打印 a 以让用户知道它已完成),以及 2) 到设备驱动程序(并且还打印文本让用户知道它也已完成)。

下面是完整的用户空间代码:

int main() {
    FILE *fp;

    fp = fopen("./test.txt","w");
    fputs("Test\n", fp);
    fclose(fp);
    printf("Printed to txt\n"); //Prints normally.

    fp = fopen("/dev/testchar", "w");        
    fputs("Test\n", fp);
    fclose(fp);
    printf("Printed to dev\n"); //Never gets to this point

    return 0;
}

当我编译并运行代码时,程序会吐出

Printed to txt

然后一直挂起,直到调用 ctrl+c。它永远不会超过第二个fputs()

在监视 kern.log 时,我看到无休止地调用写入设备驱动程序。

这里我从设备驱动中提取了相关代码:

static char msg[256] = {0};

static struct file_operations fops =
{
    .write = dev_write
};


static ssize_t dev_write(struct file *file, const char *buf, size_t len, loff_t *ppos)
{
    sprintf(msg, "Input:%s, Chars:%lu\n", buf, len);
    printk(KERN_NOTICE "%s\n", msg);

    return 0;
}

uname -r: 4.10.0-38-generic

gcc -v: gcc version 5.4.0 20160609 (Ubuntu 5.4.0-6ubuntu1~16.04.4)

我的问题是:为什么程序在写入设备时会陷入无限循环,我该如何解决?

提前致谢。任何帮助将不胜感激。

【问题讨论】:

标签: c linux kernel driver device


【解决方案1】:

我认为内核写入操作应该返回写入的字节数。您返回 0。因此 write 系统调用以 0 返回到用户空间。但是,由于您的用户空间代码正在使用 stdio,因此您的用户空间代码再次尝试写入,假设系统调用根本没有写出所有数据。如果您返回输入的长度,则 stdio 将知道所有数据已写入。或者,您可以直接使用 write 系统调用而不是 fputs。您的内核代码仍然不正确,但您的程序将终止。 您可以使用strace 对此进行测试并查看所有系统调用。

【讨论】:

  • 我将 write 系统调用的 return 0 更改为 return len 并且它起作用了。感谢您的帮助!
猜你喜欢
  • 2014-12-16
  • 2020-09-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-30
  • 2014-05-18
  • 1970-01-01
相关资源
最近更新 更多