写入 Linux 设备驱动程序导致无限循环

Writing to Linux device driver causes infinite loop

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

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

下面是完整的用户space代码:

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)

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

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

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