- 背景
使用netlink可以监控u盘相关的热插拔事件,通过查询glib相关手册发现gio中也有类似相关功能,下面看看如何使用gio来监控U盘事件。
## Gio/VolumeMonitor 简介
Gio 是一个提供I/O、网络、进程间通讯的应用级别的库。
在2.0版本中的编译依赖如下:
头文件:
gio/gdesktopappinfo.h, gio/gfiledescriptorbased.h, gio/gio.h, gio/gunixfdmessage.h, gio/gunixinputstream.h, gio/gunixmounts.h, gio/gunixoutputstream.h
pkg-config 文件:
gio-2.0, gio-unix-2.0
VolumeMonitor类:
class Gio.VolumeMonitor : GObject.Object
{
/* No available fields */
}
GVolumeMonitor可以列出用户感兴趣的Volume和设备。GVolumeMonitor不能在没有线程默认上下文活动的情况下从主线程以外的其他线程使用。
为了接收有关通过GVFS监控的卷和装载的更新,必须运行一个主循环来监听这些事件。
- 函数简介
g_volume_monitor_get
获取volume监视器
g_volume_monitor_get_connected_drives
获取连接系统的驱动器的列表
g_volume_monitor_get_mount_for_uuid
通过uuid查找GMount对象
g_volume_monitor_get_mounts
获取mounts信息
g_volume_monitor_get_volume_for_uuid
通过uuid查找GVolume对象
g_volume_monitor_get_volumes
获取系统的volume
- 事件简介信号
Gio.VolumeMonitor::mount-added
执行挂载盘后会产生
Gio.VolumeMonitor::mount-changed
mount事件
Gio.VolumeMonitor::mount-pre-unmount
拔出或者unmount
Gio.VolumeMonitor::mount-removed
磁盘被移除
- Demo
#include <glib.h>
#include <gio/gio.h>
//gcc volume.c -o volume -I /usr/lib/aarch64-linux-gnu/glib-2.0/include/ -I /usr/include/glib-2.0 -lglib-2.0 -lgobject-2.0 -lgio-2.0
static void handle_mount_changed(GVolumeMonitor* monitor, GMount* mount, gpointer data)
{
char* ev = (char*)data;
GFile* root = g_mount_get_root(mount);
gchar* path = g_file_get_path(root);
if (g_strcmp0(ev, "mount-removed") == 0) {
g_print("removed path =%s\n", path);
} else if(g_strcmp0(ev, "mount-added") == 0) {
g_print("mount path =%s\n", path);
}
g_object_unref(G_OBJECT(root));
g_free(path);
}
int main()
{
GVolumeMonitor* monitor = g_volume_monitor_get();
g_signal_connect(G_OBJECT(monitor), "mount-added",
G_CALLBACK(handle_mount_changed), "mount-added");
g_signal_connect(G_OBJECT(monitor), "mount-removed",
G_CALLBACK(handle_mount_changed), "mount-removed");
g_main_loop_run(g_main_loop_new(0,0));
return 0;
}
- 编译
gcc volume.c -o volume -I /usr/lib/aarch64-linux-gnu/glib-2.0/include/ -I /usr/include/glib-2.0 -lglib-2.0 -lgobject-2.0 -lgio-2.0
- 运行
./volume
插拔U盘即可以看到log信息。
- 参考资料
https://gitlab.gnome.org/GNOME/glib/
https://docs.gtk.org/gio/index.html