1

I want to get devnum for a specific tty e.g. /dev/ttyUSB1. To do so I modified the answer https://stackoverflow.com/a/20341112/2429333 as follows:

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;
}

What I don't like about this solution is that I have to iterate over all those list entries in a specific subsystem. Is there a way I can use devnode information (filename) to get the portnum with libudev?

1 Answer 1

0

Devices which present a "traditional" file I/O style interface to user space can be uniquely identified (for historical reasons) using a combination of their devnum (composed of major+minor number), and type (character or block).

A libudev device can be created by calling udev_device_new_from_devnum() with the type and devnum as parameters.

Given a filesystem path to the device, you can use one of the c library stat() family of calls to discover the type and devnum.

The devnum you need will be in the st_rdev member of the stat struct.

The type can be inferred from the contents of the st_mode member. Check if st_mode & S_IFMT is equal to S_ISCHR or S_ISBLK respectively. Based on this test result, pass either 'c' or 'b' as the type argument.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.