Linux用户态应用通过ioctl调用USB API的正确性及设备文件名问询
Answer
Great question! Let's break this down step by step to address both your questions.
1. Is your implementation correct?
Your core approach using ioctl with USBDEVFS_GETDRIVER is on the right track, but there are a few critical details missing to make it robust and functional:
- Missing error checking: You should always validate the return values of
open()andioctl()—they can fail for various reasons (like permission issues, invalid device path, or unsupported interface). - Uninitialized struct field: The
usbdevfs_getdriverstruct requires you to set theinterfacefield to specify which USB interface you want to query the driver for. USB devices often have multiple interfaces, so this is mandatory.
With those fixes, the implementation becomes valid.
2. What should "device_file_name" be?
This path refers to the character device file corresponding to your target USB device. These files are located in the /dev/bus/usb/ directory, organized by bus number and device number. Here's how to find the correct path:
- Run the
lsusbcommand in your terminal. You'll see output like this:Bus 001 Device 005: ID 1234:5678 Example USB Device - The bus number is
001and the device number is005, so the full path would be/dev/bus/usb/001/005.
Important notes about permissions:
- By default, regular users don't have read/write access to these device files. You'll need to run your program with
sudo, or set up a udev rule to grant permissions to your user or group.
Corrected Example Code
Here's an updated version of your code with error handling and proper struct initialization:
#include <stdio.h> #include <fcntl.h> #include <unistd.h> #include <sys/ioctl.h> #include <linux/usbdevice_fs.h> int main() { struct usbdevfs_getdriver usbdriver = {0}; // Set the interface number to query (adjust this based on your device's interfaces) usbdriver.interface = 0; // Replace with your actual device file path from lsusb int fd = open("/dev/bus/usb/001/005", O_RDWR); if (fd == -1) { perror("Failed to open USB device file"); return 1; } int ret = ioctl(fd, USBDEVFS_GETDRIVER, &usbdriver); if (ret == -1) { perror("ioctl USBDEVFS_GETDRIVER failed"); close(fd); return 1; } printf("Loaded driver for interface %d: %s\n", usbdriver.interface, usbdriver.driver); close(fd); return 0; }
内容的提问来源于stack exchange,提问作者Kallel Omar
相关产品推荐
相关产品推荐

