我想获得devnum
特定的tty,例如/dev/ttyUSB1
。为此,我修改了答案https://stackoverflow.com/a/20341112/2429333,如下所示:
int get_devnum(const char *filename)
{
if( filename == NULL) return -1;
int retval;
const char *path;
const char *sysattr;
struct udev *udev;
struct udev_enumerate *enumerate;
struct udev_list_entry *devices, *dev_list_entry;
struct udev_device *dev;
retval = -1;
udev = udev_new();
enumerate = udev_enumerate_new(udev);
udev_enumerate_add_match_subsystem(enumerate, "tty");
udev_enumerate_scan_devices(enumerate);
devices = udev_enumerate_get_list_entry(enumerate);
udev_list_entry_foreach(dev_list_entry, devices) {
path = udev_list_entry_get_name(dev_list_entry);
dev = udev_device_new_from_syspath(udev, path);
if(strcmp(udev_device_get_devnode(dev), filename) == 0)
{
dev = udev_device_get_parent_with_subsystem_devtype(
dev,
"usb",
"usb_device");
sysattr = udev_device_get_sysattr_value(dev, "devnum");
if(sysattr != NULL)
{
retval = strtol(sysattr, NULL, 10);
}
udev_device_unref(dev);
break;
}
udev_device_unref(dev);
}
udev_enumerate_unref(enumerate);
udev_unref(udev);
return retval;
}
我不喜欢这个解决方案是我必须迭代特定子系统中的所有列表条目。有没有办法可以使用devnode信息(文件名)来获取带有libudev的portnum
?