【问题标题】:can we check a file's read write permission before opening it in kernel我们可以在内核中打开文件之前检查文件的读写权限吗
【发布时间】:2019-03-09 00:10:06
【问题描述】:

我想在内核中以只读模式打开一个文件,但在此之前我想检查该文件是否具有读取权限,我该如何检查它?因为要检查我是否需要一个指向输入文件的文件指针。

filp_open(args->inputfile, O_RDONLY, 0);

有什么方法可以在打开之前检查它吗?我尝试使用,但总是失败

if (!fileptr->f_op->read)
{
     error = -EACCES;
     printk("reading input file failed\n");
}

【问题讨论】:

  • 问题是在检查权限和打开之间存在竞争条件,其中所述权限可以被其他东西更改。只需尝试打开它并适当地处理故障。
  • 有趣的是,accepted 答案中的 user-space 代码如何适用于 kernel-space代码...

标签: c linux file permissions kernel


【解决方案1】:

您应该使用检查文件访问权限的access(char *filepath,int mode)

mode描述您要检查的内容:F_OK(存在),或 R_OK(读取)、W_OK(写入)或 X_OK(执行)的 OR 组合。

所以对于你的问题,你可以使用:

#include <unistd.h>
...

if( access( filename, R_OK ) != -1 ) {
    // can read file
} else {
    // cannot read file
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-08
    • 1970-01-01
    • 2012-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-22
    相关资源
    最近更新 更多