使用systemd/sd-device枚举BLOCK设备时返回NULL的问题求助
问题解决:sd_device_enumerator遍历设备返回NULL
核心原因
你的代码在初始化枚举器并设置子系统匹配规则后,缺少了设备扫描步骤。sd_device_enumerator需要先调用sd_device_enumerator_scan_devices()来扫描系统中的设备,否则枚举器内部没有设备数据,调用sd_device_enumerator_get_device_next()自然会返回NULL。
修改后的代码
#include "main.h" int test0() { int r; sd_device_enumerator *enumerator = NULL; sd_device *dev = NULL; // Initialize the Device-Enumerator r = sd_device_enumerator_new(&enumerator); if (r < 0) { printf("Error | Initialize the Device-Enumerator: %s\n", strerror(-r)); return 1; // 初始化失败直接返回,避免后续操作空指针 } // Set Filter to BLOCK r = sd_device_enumerator_add_match_subsystem(enumerator, "block", 0); if (r < 0) { printf("Error | Set Filter to BLOCK: %s\n", strerror(-r)); sd_device_enumerator_unref(enumerator); return 1; } // 关键步骤:扫描系统中的block设备 r = sd_device_enumerator_scan_devices(enumerator); if (r < 0) { printf("Error | Scan BLOCK devices: %s\n", strerror(-r)); sd_device_enumerator_unref(enumerator); return 1; } // Loop to run through all BLOCK devices while ((dev = sd_device_enumerator_get_device_next(enumerator)) != NULL) { const char *sysname = NULL; const char *pt_type = NULL; // 获取设备的sysname(比如sda、sdb等) r = sd_device_get_sysname(dev, &sysname); if (r >= 0) { printf("Device: %s\n", sysname); } r = sd_device_get_property_value(dev, "ID_PART_TABLE_TYPE", &pt_type); if (r >= 0) { printf("ID_PART_TABLE_TYPE: %s\n", pt_type); } else { // 没有该属性时的提示,可选 printf("ID_PART_TABLE_TYPE: (not set)\n"); } sd_device_unref(dev); dev = NULL; cout << "loop" << endl; } if (enumerator) { sd_device_enumerator_unref(enumerator); } if (dev) { sd_device_unref(dev); } return 0; } int main() { test0(); return 0; }
其他细节修正
- 添加扫描步骤:新增
sd_device_enumerator_scan_devices(enumerator)调用,这是让枚举器获取设备列表的关键操作。 - 完善错误处理:初始化或设置规则失败时,及时释放资源并返回,避免空指针操作。
- 修复printf参数缺失:原代码中
printf("Device: %s\n")没有对应参数,新增sd_device_get_sysname获取设备名称并补充到printf中。 - 属性不存在的提示:当设备没有
ID_PART_TABLE_TYPE属性时(比如非磁盘的block设备,如loop设备),给出明确提示,避免混淆。
内容的提问来源于stack exchange,提问作者user21053811
相关产品推荐
相关产品推荐

