如何创建程序列出Mac中的所有USB设备?

Dil*_*ili 18 c++ macos xcode iokit

我对Mac OS X操作系统的了解有限,现在我开始使用Xcode并正在研究I/O工具包.我需要在命令行工具下在Xcode中创建一个程序,以便列出Mac系统中连接的所有USB设备.那些以前有过这方面经验的人,请帮助我.如果有人能为我提供示例代码,那么它将非常有用,因为我正在寻找起点.

Has*_*kun 20

您可以根据需要调整USBPrivateDataSample,示例设置通知程序,列出当前连接的设备,然后等待设备连接/分离.如果这样做,您将需要删除usbVendorusbProduct匹配的词典,因此所有USB设备都匹配.

或者,您可以使用IOServiceGetMatchingServices创建的字典来获取所有当前匹配服务的迭代器IOServiceMatching(kIOUSBDeviceClassName).

这是一个简短的样本(我从未运行过):

#include <IOKit/IOKitLib.h>
#include <IOKit/usb/IOUSBLib.h>

int main(int argc, const char *argv[])
{
    CFMutableDictionaryRef matchingDict;
    io_iterator_t iter;
    kern_return_t kr;
    io_service_t device;

    /* set up a matching dictionary for the class */
    matchingDict = IOServiceMatching(kIOUSBDeviceClassName);
    if (matchingDict == NULL)
    {
        return -1; // fail
    }

    /* Now we have a dictionary, get an iterator.*/
    kr = IOServiceGetMatchingServices(kIOMasterPortDefault, matchingDict, &iter);
    if (kr != KERN_SUCCESS)
    {
        return -1;
    }

    /* iterate */
    while ((device = IOIteratorNext(iter)))
    {
        /* do something with device, eg. check properties */
        /* ... */
        /* And free the reference taken before continuing to the next item */
        IOObjectRelease(device);
    }

   /* Done, release the iterator */
   IOObjectRelease(iter);
   return 0;
}
Run Code Online (Sandbox Code Playgroud)

  • 您需要在项目中使用I/O Kit框架(即`IOKit.framework`)和Core Foundation框架,否则这将无法链接. (3认同)
  • /***显示设备名称***/.................... io_name_t deviceName; kr = IORegistryEntryGetName(device,deviceName); if(KERN_SUCCESS!= kr){deviceName [0] ='\ 0'; } printf("\ndeviceName:%s",deviceName); .........................这给了我设备名称......现在我正在寻找对于动态的程序,它也显示设备的附加和分离..帮助 (3认同)

Pau*_*l R 7

您只需要访问IOKit Registry.您可以使用该ioreg工具执行此操作(例如,通过system()或运行它popen()).如果没有,那么您至少可以使用它来验证您的代码:

ioreg工具信息:

$ man ioreg
Run Code Online (Sandbox Code Playgroud)

获取USB设备列表:

$ ioreg -Src IOUSBDevice
Run Code Online (Sandbox Code Playgroud)

  • 您是否阅读过使用`system()`或`popen()`从代码中执行ioreg工具的部分? (2认同)