You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ubuntu 22.04下g_volume_monitor_get_connected_drives返回NULL的问题排查及解决分享

Ubuntu 22.04下g_volume_monitor_get_connected_drives返回NULL的问题排查及解决分享

最近在刚安装的Ubuntu 22.04上为新项目调试GIO系统,一开始就碰到了头疼的问题:我想通过GVolumeMonitor获取已连接的驱动器,但调用g_volume_monitor_get_connected_drives()总是返回NULL,可命令行里执行gio mount -l明明能看到所有挂载的驱动器和卷。

先给大家看看我最开始的测试代码:

int main(){
    GVolumeMonitor* monitor = g_volume_monitor_get();
    GList* drives = g_volume_monitor_get_connected_drives(monitor);
    return 0;
}

编译参数我也确认过没问题,包含了所有必要的头文件路径和依赖库:

/usr/bin/g++ -fdiagnostics-color=always -I/usr/include/glib-2.0 -I/usr/lib/x86_64-linux-gnu/glib-2.0/include -pthread -I/usr/include/libmount -I/usr/include/blkid -I/usr/include/gio-unix-2.0 -g /home/user/dev/start/main.cpp -o /home/user/dev/start/main -L/usr/lib -L/usr/lib/x86_64-linux-gnu -lgio-2.0 -lgobject-2.0 -lglib-2.0

排查尝试

  1. 我以为是没有启动GMainLoop导致GIO的异步初始化没完成,于是修改代码加上了主循环:
GMainLoop* mainLoop = g_main_loop_new(NULL, true);
GVolumeMonitor* monitor = g_volume_monitor_get();
GList* drives = g_volume_monitor_get_connected_drives(monitor);

结果还是一样,drives依然是NULL。

  1. 换个思路,试试GIO的Unix挂载点相关接口,代码如下:
void unix_mount_points_iterator_func(gpointer data, gpointer user_data){
    GUnixMountPoint* mount_point = (GUnixMountPoint*) data;
    if(NULL != mount_point){
        const char* mount_path = g_unix_mount_point_get_mount_path(mount_point);
        std::cout << mount_path << std::endl;
    }
}

// 主函数里调用
guint64 time_read_mount_points;
GList* mount_points = g_unix_mount_points_get(&time_read_mount_points);
g_list_foreach(mount_points, &unix_mount_points_iterator_func, NULL);

这次居然成功了,能输出所有挂载点,比如/、/boot还有我挂载的WebDAV路径,说明GIO的基础功能是正常的,问题应该出在VolumeMonitor相关的加载逻辑上。

最终解决方法

折腾了半天,最后发现居然是VS Code的问题!原来我是从Ubuntu应用商店安装的VS Code,它的某种缓存机制导致程序没有链接系统默认的libgio库。后来我卸载了应用商店版本,从微软官方仓库重新安装VS Code后,再运行最开始的那段简单代码,g_volume_monitor_get_connected_drives()终于能正常返回驱动器列表了!

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.08 11:53:10