You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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() and ioctl()—they can fail for various reasons (like permission issues, invalid device path, or unsupported interface).
  • Uninitialized struct field: The usbdevfs_getdriver struct requires you to set the interface field 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 lsusb command in your terminal. You'll see output like this:
    Bus 001 Device 005: ID 1234:5678 Example USB Device
    
  • The bus number is 001 and the device number is 005, 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 09:01:46