Linux:检查进程是否对C / C ++中的文件具有读访问权限

时间:2013-02-13 21:10:16

标签: c++ c linux pid

假设我们有一些PID和绝对文件路径[不是符号链接,只是常规文件] - 确定PID对此文件具有读取权限的最有效方法是什么?

2 个答案:

答案 0 :(得分:4)

我只知道一种方法。首先,通过构造路径/proc/ + PID来查找进程的UID和GID。例如/proc/4261。然后stat()该路径并获取其UID和GID。然后,stat()要检查读取访问权限的文件,并检查进程的UID / GID是否具有读取权限:

(假设您已经在path_to_proc中构建了“/ proc / [PID]”路径。)

struct stat buf;

// Get UID and GID of the process.
stat(path_to_proc, &buf);
uid_t proc_uid = buf.st_uid;
gid_t proc_gid = buf.st_gid;

// Get UID and GID of the file.
stat(path_to_file_you_want_to_check, &buf);

// If the process owns the file, check if it has read access.
if (proc_uid == buf.st_uid && buf.st_mode & S_IRUSR) {
    // Yes, the process has read access.
}

// Check if the group of the process's UID matches the file's group
// and if so, check for read/write access.
else if (proc_gid == buf.st_gid && buf.st_mode & S_IRGRP) {
    // Yes, the process has read access.
}

// The process's UID is neither the owner of the file nor does its GID
// match the file's.  Check whether the file is world readable.
else if (buf.st_mode & S_IROTH) {
    // Yes, the process has read access.
}

请注意,代码并不完美。如果没有用户的主要组,它不会处理进程用户实际属于文件组的可能性。要处理这个问题,你需要使用getgrouplist()(这意味着你需要先将进程UID转换为包含实际用户名的字符串,然后将所有返回的组与文件的组进行比较,如果匹配,检查组读访问(S_IRGRP)。)

答案 1 :(得分:1)

打开文件。这才是真正了解的唯一方法。涉及stat(2)的答案要求您编写代码来解释权限位并将它们与您的活动uid / gid和补充组进行比较。在任何情况下,它在一般情况下都是不完整的:像selinux或apparmor这样的LSM钩子也可以在传统Unix权限模型未捕获的文件上实现权限模型。