简体   繁体   中英

Linux Kernel Module File close not quite correct

I have a small problem with this code. I can't figure out why it is not working.

static int test(const char *path)
{
    struct file *filp;
    filp = filp_open(path, O_RDONLY, 0);
    if (IS_ERR(filp))
        return filp;
    // some code (only read from filp (like inode and stuff))
    filp_close(filp, NULL);
}

When I use this snippet once or twice or even a thousand times it works but after approximately 63000 times I run into error -23 and after that cann't open a single file. I looked up the syscalls for open and close and these use filp_open/filp_close and I just can't figure out what is wrong with this code. It must be something with the file descriptors not being deallocated, but why?

Try this:

mm_segment_t  st_old_fs;      
st_old_fs = get_fs();
set_fs(get_ds());

struct file *filp;
filp = file_open(path, O_RDONLY, 0);
if (IS_ERR(filp))
{
    set_fs(st_old_fs);
    return filp;
}
// some code (only read from filp (like inode and stuff))
filp_close(filp, NULL);

set_fs(st_old_fs);

The kernel has some special memory manager way for the file. So you need to save the old way and restore it after use the file_open.

file objects, like plenty others, are freed only after RCU grace period finishes. I suspect your kernel is not preemptible and you don't context switch anywhere, thus the grace period never completes and the objects accumulate. You can learn more about rcu here: https://lwn.net/Articles/262464/

The real question is what are you doing. Kernel-level work is not fit for programming beginners. If this is a college assignment, it is extremely likely you are going about it wrong or the assignment itself is just bad.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM