Siddhant Siddhant - 2 years ago 505
Linux Question

How can I get a filename from a file descriptor inside a kernel module?

I need to get the name of a file from a given file descriptor, inside a small linux kernel module that I wrote. I tried the solution given at Getting Filename from file descriptor in C, but for some reason, it prints out garbage values (on using

as mentioned in the solution). How can I do it?

caf caf
Answer Source

Don't call SYS_readlink - use the same method that procfs does when one of those links is read. Start with the code in proc_pid_readlink() and proc_fd_link() in fs/proc/base.c.

Broadly, given an int fd and a struct files_struct *files from the task you're interested in (which you have taken a reference to), you want to do:

char *tmp;
char *pathname;
struct file *file;
struct path *path;

file = fcheck_files(files, fd);
if (!file) {
    return -ENOENT;

path = &file->f_path;

tmp = (char *)__get_free_page(GFP_TEMPORARY);

if (!tmp) {
    return -ENOMEM;

pathname = d_path(path, tmp, PAGE_SIZE);

if (IS_ERR(pathname)) {
    free_page((unsigned long)tmp);
    return PTR_ERR(pathname);

/* do something here with pathname */

free_page((unsigned long)tmp);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download