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

How can I read a folder owned by root with Vala?

我正在尝试使用以下权限读取路径 /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

如果您 运行 作为普通用户使用您的应用程序,则必须排除 "partial" 目录,它具有更严格的权限 (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