struct file_operations的read调用中的未知循环

时间:2013-12-23 18:49:32

标签: linux-kernel linux-device-driver

我正在尝试创建一个虚拟汽车作为内核模块(用于练习)。 我有一个带有struct file_operations的读回调。 这是我的阅读方法

 ssize_t vcar_read(struct file *file,char __user *buf,size_t len,loff_t *offset){

    int byte_to_read,maxbyte,byte_Read;
    printk(KERN_INFO "[VCAR] Starting reading Car's Status\n");
    maxbyte=ramspace - *offset;
    byte_to_read=maxbyte>len?len:maxbyte;
    if(byte_to_read==0)
    {
        printk(KERN_INFO"[VCAR] Reached End of message\n");
    }
        sprintf(ramdisk,"Current Status of Virtual Car \n\
            Direction:%s\n\
            Speed:%lf\n\
            Accelarating With:%d\n \
            Maxspeed:%d\n",getDirection(vcar->direction)
            ,vcar->speed,vcar->accelaration,vcar->maxspeed);
        byte_Read=byte_to_read-copy_to_user(buf,ramdisk+*offset,byte_to_read);
        *offset+=byte_Read;
        printk(KERN_INFO "[VCAR] Car's Status Copied to userspace\n");
        return strlen(ramdisk);
}

当我尝试使用cat读取默认值时,输出是正确的,但它也包含不需要的字符串,看起来像是内存泄漏,或者我错误地读取了其他内存。

这是输出

root@anandlinux:/dev# more "Virtual_Car"
Current Status of Virtual Car 
                        Direction:UNKOWN
                        Speed:%f
                        Accelarating With:10
                        Maxspeed:100


dComposxMdComponentLevelsponentLevelAtaSmartBlobLevelrtBlobdComposxMdComponentLevelsponentLevelAtaSmartBlobLevelrtBlobdComposxMdComponentLevelsponentLevelAtaSmartBlobLevelrtBlobdComposxMdCompodComposxMdComponentLevelsponentLevelAtaSmartBlobLevelrtBlobdComposxMdComponentLevelsponentLevelAtaSmartBlobLevelr

dmesg显示读回调进入循环。这是dmesg

的输出
[ 8690.506307] [VCAR] Starting ramdisk Allocation
[ 8690.506323] [VCAR] Ramdisk Allocated
[ 8690.506326] [VCAR] Opening File
[ 8690.506366] [VCAR] Starting reading Car's Status
[ 8690.506384] [VCAR] Car's Status Copied to userspace
[ 8690.506603] [VCAR] Starting reading Car's Status
[ 8690.506610] [VCAR] Car's Status Copied to userspace
[ 8690.506631] [VCAR] Starting reading Car's Status
[ 8690.506637] [VCAR] Car's Status Copied to userspace
[ 8690.506657] [VCAR] Starting reading Car's Status
[ 8690.506662] [VCAR] Car's Status Copied to userspace
[ 8690.506681] [VCAR] Starting reading Car's Status
[ 8690.506687] [VCAR] Car's Status Copied to userspace
[ 8690.506706] [VCAR] Starting reading Car's Status
[ 8690.506712] [VCAR] Car's Status Copied to userspace
[ 8690.506731] [VCAR] Starting reading Car's Status
[ 8690.506736] [VCAR] Car's Status Copied to userspace
[ 8690.506756] [VCAR] Starting reading Car's Status
[ 8690.506761] [VCAR] Car's Status Copied to userspace
[ 8690.506793] [VCAR] Starting reading Car's Status
[ 8690.506799] [VCAR] Car's Status Copied to userspace
[ 8691.399452] [VCAR] Releasing Ramdisk

请帮我找到错误。 完整代码在http://kgcorner.com/code/car.c

1 个答案:

答案 0 :(得分:0)

我最终解决了它并摆脱了误解。 实际上read函数返回读取的字节数(我知道这个) 它会被召回,直到它返回0(不知道这一点)。 我在同一个链接上更新了代码。 http://kgcorner.com/code/car.c