0

Trying a file creation under /tmp like below:

struct file *fp;
fp = file_open("/tmp/sample-logfile",O_CREAT|O_WRONLY|O_TRUNC, 0666);
if (IS_ERR(fp))
printk("<0>Create record file error!\n\r");
file_close(fp);

After the kernel comes-up, there is no file visible. There are no errors also shown during kernel bootup. Now sure what is going wrong here?

My file_open is like this:

struct file *file_open(const char *path, int flags, int rights) 
{
    struct file *filp = NULL;
    mm_segment_t oldfs;
    int err = 0;

    oldfs = get_fs();
    set_fs(get_ds());
    filp = filp_open(path, flags, rights);
    set_fs(oldfs);
    if (IS_ERR(filp)) {
        err = PTR_ERR(filp);
        return NULL;
    }
    return filp;
}
Ravi
  • 239
  • 2
  • 14
  • 1
    Did you follow a tutorial for kernel programming? Add links to your question. The use of `IS_ERR` in combination with your `return NULL` looks suspicious. AFAIK `IS_ERR` or `IS_ERR_VALUE` does not cover `NULL`. – Bodo Aug 14 '23 at 17:01
  • Which kernel **version** do you use? Modern Linux kernel doesn't require `get_fs`/`set_fs` for use files: https://stackoverflow.com/a/53917617/3440745 – Tsyvarev Aug 14 '23 at 17:21
  • How do you know your code is called? – stark Aug 15 '23 at 12:45
  • @Bodo Indeed, `IS_ERR(NULL)` is false. There is `IS_ERR_OR_NULL(ptr)` which returns `ptr==NULL || IS_ERR(ptr)`. – Ian Abbott Aug 18 '23 at 16:28
  • ASIDE: `printk("<0>Create record file error!\n\r");` should be `printk(KERN_EMERG "Create record file error!\n");`. Do not put `\r` on the end! – Ian Abbott Aug 18 '23 at 16:30
  • You could add this to your `file_open` function before returning `NULL` to see the error number in the kernel log (since you decided not to pass the error number back to the caller): `printk(KERN_ERR "failed to open '%s' - err %d\n", path, err);`. – Ian Abbott Aug 18 '23 at 16:38

0 Answers0