Note that there are some explanatory texts on larger screens.

plurals
  1. POlibudev how to use poll with the file descriptor
    text
    copied!<p>So, I have an application that I want to be notified of hotplug events on linux. Naturally, I looked at libudev and its <a href="https://www.kernel.org/pub/linux/utils/kernel/hotplug/libudev/api-index-full.html" rel="nofollow">API</a>. I also found a useful <a href="http://www.signal11.us/oss/udev/" rel="nofollow">tutorial</a> on how to use select() with libudev. Following the tutorial and glancing at the API, I came up with this example program that waits for hotplug events and then outputs some basic information about the device that was just added or removed.</p> <pre><code>#include &lt;poll.h&gt; #include &lt;libudev.h&gt; #include &lt;stdexcept&gt; #include &lt;iostream&gt; udev* hotplug; udev_monitor* hotplug_monitor; void init() { // create the udev object hotplug = udev_new(); if(!this-&gt;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) &gt; 0) { // XXX std::cout &lt;&lt; "hotplug[ " &lt;&lt; items[0].revents &lt;&lt; " ]" &lt;&lt; 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 &lt;&lt; "hotplug[" &lt;&lt; udev_device_get_action(dev) &lt;&lt; "] "; std::cout &lt;&lt; udev_device_get_devnode(dev) &lt;&lt; ","; std::cout &lt;&lt; udev_device_get_subsystem(dev) &lt;&lt; ","; std::cout &lt;&lt; udev_device_get_devtype(dev) &lt;&lt; std::endl; // destroy the relevant device udev_device_unref(dev); // XXX std::cout &lt;&lt; "done" &lt;&lt; std::endl; // clear the revents items[0].revents = 0; } } int main(int args, char* argv[]) { init(); while(true) { run(); } deinit(); } </code></pre> <p>Well, it doesn't work. Here's the output I get when I plug in a usb mouse.</p> <pre><code>hotplug[ 1 ] hotplug[add] /dev/bus/usb/008/002,usb,usb_device done hotplug[ 1 ] hotplug[add] </code></pre> <p>At that point the program freezes and I have to stop it with Ctrl-C. What am I doing wrong?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload