linux内核编程无限循环

时间:2014-12-01 07:18:53

标签: c linux kernel

全新的linux内核编程,想知道为什么我的设备读写时会抛出无限循环:

echo "hi" > simpchar
cat simpchar

static ssize_t device_read(struct file *filp, char *buff,
        size_t len, loff_t * off)
{
    int bytes_read = 0;
    int idxr = 0;
    while (len && (msg[idxr] != 0)) {
        put_user(msg[idxr], buff++);
        len--;
        bytes_read++;
        idxr++;
    }   
    return bytes_read;
}

static ssize_t device_write(struct file *filp, const char *buff,
        size_t len, loff_t * off)
{
    int bytes_read = 0;
    memset(msg, 0, BUF_LEN);
    int idxr = 0;
    while (len > 0) {
        msg[idxr++] = buff[idxr++];  
        len--;
        bytes_read++;
    }   
    return bytes_read;
}

2 个答案:

答案 0 :(得分:1)

您在此处缺少的是loff_t * off的更新。 这是文件描述符与文件中的位置保持同步的方式。

在您的代码中,每次调用read()/ write()始终从偏移量0开始。

请参阅how-to-test-your-own-linux-module

答案 1 :(得分:1)

虽然有一个小错误。你已经将idxr ++作为消息[idxr ++] = buffer [idxr ++]。这会使idxr增加两次,所以即使它没有进入无限循环,你也不会得到你的结果。创建一个新变量,说count = 0并尝试返回计数。