如何使用Vala读取root拥有的文件夹?

时间:2016-08-03 02:22:43

标签: directory file-permissions vala apt file-listing

我正在尝试使用以下权限读取路径/var/cache/apt/archives

drwxr-xr-x 3 root root 90112 ago 2 14:36 archives

我收到以下错误:

ERROR: Error opening directory '/var/cache/apt/archives/partial': Permission denied

有人可以帮我一把吗?

源代码如下:

using Gtk;
using GLib;

private int64[] get_folder_data (File file, string space = "",     Cancellable? cancellable = null) throws Error
{
    FileEnumerator enumerator = file.enumerate_children (
    "standard::*",
    FileQueryInfoFlags.NOFOLLOW_SYMLINKS, 
    cancellable);

    int64 files = 0;
    int64 size  = 0;
    int64[] data = new int64[2];
    FileInfo info = null;

    while (cancellable.is_cancelled () == false && ((info = enumerator.next_file (cancellable)) != null)) {
        if (info.get_file_type () == FileType.DIRECTORY) {
            File subdir = file.resolve_relative_path (info.get_name ());
            get_folder_data (subdir, space + " ", cancellable);
        } else {
            files += 1;//Sum Files
            size  += info.get_size ();//Accumulates Size
        }
    }

    if (cancellable.is_cancelled ()) {
        throw new IOError.CANCELLED ("Operation was cancelled");
    }

    data[0] = files;
    data[1] = size;

    stdout.printf ("APT CACHE SIZE: %s\n", files.to_string());
    stdout.printf ("APT CACHE FILES: %s\n", size.to_string());

    return data;
}

public static int main (string[] args) {
    Gtk.init (ref args);

    File APT_CACHE_PATH = File.new_for_path ("/var/cache/apt/archives");
    try {
        get_folder_data (APT_CACHE_PATH, "", new Cancellable ());
    } catch (Error e) {
        stdout.printf ("ERROR: %s\n", e.message);    
    }
    Gtk.main ();
    return 0;
}

我用于编译的命令如下:

valac --pkg gtk+-3.0 --pkg glib-2.0 --pkg gio-2.0 apt-cache.vala

1 个答案:

答案 0 :(得分:0)

如果您以普通用户身份运行应用,则必须排除"部分" dir,它有更多限制权限(0700):

drwx------ 2 _apt root 4096 Jul 29 11:36 /var/cache/apt/archives/partial

排除部分目录的一种方法是忽略任何无法访问的目录:

int64[] data = new int64[2];
FileEnumerator enumerator = null;
try {
    enumerator = file.enumerate_children (
        "standard::*",
        FileQueryInfoFlags.NOFOLLOW_SYMLINKS,
        cancellable);
}
catch (IOError e) {
    stderr.printf ("WARNING: Unable to get size of dir '%s': %s\n", file.get_path (), e.message);
    data[0] = 0;
    data[1] = 0;
    return data;
}

此外,始终明确忽略部分文件夹可能是个好主意。

如果您计划让实用程序对root用户也有用,您甚至可以考虑添加命令行选项,例如" - include-partial-dir"。

使用简单的bash命令也可以做到同样的事情,这比编写自己的程序容易得多。

du -sh /var/cache/apt/archives
find /var/cache/apt/archives -type f | wc -l

请注意,dufind也警告无法访问的部分目录:

$ du -sh /var/cache/apt/archives
du: cannot read directory '/var/cache/apt/archives/partial': Permission denied
4.6G    /var/cache/apt/archives

$ find /var/cache/apt/archives -type f | wc -l
find: '/var/cache/apt/archives/partial': Permission denied
3732