linux下获取设备的bus和device编号C++
时间: 2024-03-01 19:55:30 浏览: 246
要在Linux下获取设备的bus和device编号,可以使用libudev库,以下是示例C++代码:
```c++
#include <iostream>
#include <libudev.h>
int main() {
struct udev *udev = udev_new();
if (!udev) {
std::cerr << "Failed to create udev context" << std::endl;
return 1;
}
struct udev_enumerate *enumerate = udev_enumerate_new(udev);
if (!enumerate) {
std::cerr << "Failed to create udev enumerate context" << std::endl;
udev_unref(udev);
return 1;
}
udev_enumerate_add_match_subsystem(enumerate, "usb");
udev_enumerate_scan_devices(enumerate);
struct udev_list_entry *devices = udev_enumerate_get_list_entry(enumerate);
struct udev_list_entry *entry;
udev_list_entry_foreach(entry, devices) {
const char *path = udev_list_entry_get_name(entry);
struct udev_device *dev = udev_device_new_from_syspath(udev, path);
if (!dev) {
std::cerr << "Failed to create udev device context" << std::endl;
continue;
}
const char *bus = udev_device_get_property_value(dev, "ID_BUS");
const char *device = udev_device_get_property_value(dev, "ID_SERIAL_SHORT");
std::cout << "Bus: " << bus << ", Device: " << device << std::endl;
udev_device_unref(dev);
}
udev_enumerate_unref(enumerate);
udev_unref(udev);
return 0;
}
```
这段代码会列出所有USB设备的bus和device编号。你可以根据需要修改`udev_enumerate_add_match_subsystem`函数的参数,来获取其他类型的设备的信息。
阅读全文