首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >libudev如何将轮询与文件描述符一起使用

libudev如何将轮询与文件描述符一起使用
EN

Stack Overflow用户
提问于 2012-04-24 04:54:50
回答 1查看 4.3K关注 0票数 2

因此,我有一个应用程序,我希望在linux上的热插拔事件时得到通知。当然,我看了看libudev和它的API。我还发现了一个关于如何在libudev中使用select()的有用tutorial。按照教程并浏览一下API,我想出了这个示例程序,它等待热插拔事件,然后输出一些关于刚刚添加或删除的设备的基本信息。

代码语言:javascript
复制
#include <poll.h>
#include <libudev.h>
#include <stdexcept>
#include <iostream>

udev* hotplug;
udev_monitor* hotplug_monitor;

void init()
{
  // create the udev object
  hotplug = udev_new();
  if(!this->hotplug)
  {
    throw std::runtime_error("cannot create udev object");
  }

  // create the udev monitor
  hotplug_monitor = udev_monitor_new_from_netlink(hotplug, "udev");

  // start receiving hotplug events
  udev_monitor_enable_receiving(hotplug_monitor);
}

void deinit()
{
  // destroy the udev monitor
  udev_monitor_unref(hotplug_monitor);

  // destroy the udev object
  udev_unref(hotplug);
}

void run()
{
  // create the poll item
  pollfd items[1];
  items[0].fd = udev_monitor_get_fd(hotplug_monitor);
  items[0].events = POLLIN;
  items[0].revents = 0;

  // while there are hotplug events to process
  while(poll(items, 1, 50) > 0)
  {
    // XXX
    std::cout << "hotplug[ " << items[0].revents << " ]" << std::endl;

    // receive the relevant device
    udev_device* dev = udev_monitor_receive_device(hotplug_monitor);
    if(!dev)
    {
      // error receiving device, skip it
      continue;
    }

    // XXX
    std::cout << "hotplug[" << udev_device_get_action(dev) << "] ";
    std::cout << udev_device_get_devnode(dev) << ",";
    std::cout << udev_device_get_subsystem(dev) << ",";
    std::cout << udev_device_get_devtype(dev) << std::endl;

    // destroy the relevant device
    udev_device_unref(dev);

    // XXX
    std::cout << "done" << std::endl;

    // clear the revents
    items[0].revents = 0;
  }
}

int main(int args, char* argv[])
{
  init();

  while(true)
  {
    run();
  }

  deinit();
}

好吧,这不管用。这是我插入usb鼠标时得到的输出。

代码语言:javascript
复制
hotplug[ 1 ]
hotplug[add] /dev/bus/usb/008/002,usb,usb_device
done
hotplug[ 1 ]
hotplug[add]

在这一点上,程序冻结,我必须停止它的Ctrl-C。我做错了什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-04-24 05:27:42

程序实际上不会停止;它会继续运行,但是当您尝试打印空字符串时,std::cout会变得混乱(并不是所有事件都具有所有属性)。修复方法是使三个打印(devnode、subsystem、devtype)具有条件。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10288158

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档