| 1 | extern crate libudev_sys as udev; |
| 2 | extern crate libc; |
| 3 | |
| 4 | use std::str; |
| 5 | |
| 6 | use std::ffi::{CString,CStr}; |
| 7 | |
| 8 | use self::libc::{c_int,c_short,c_char}; |
| 9 | |
| 10 | |
| 11 | #[cfg(target_os = "linux")] |
| 12 | #[allow(non_camel_case_types)] |
| 13 | type nfds_t = libc::c_ulong; |
| 14 | |
| 15 | #[cfg(not(target_os = "linux"))] |
| 16 | #[allow(non_camel_case_types)] |
| 17 | type nfds_t = libc::c_uint; |
| 18 | |
| 19 | #[repr(C)] |
| 20 | struct PollFd { |
| 21 | fd: c_int, |
| 22 | events: c_short, |
| 23 | revents: c_short |
| 24 | } |
| 25 | |
| 26 | const POLLIN: c_short = 0x0001; |
| 27 | |
| 28 | extern "C" { |
| 29 | fn poll(fds: *mut PollFd, nfds: nfds_t, timeout: c_int) -> c_int; |
| 30 | } |
| 31 | |
| 32 | |
| 33 | fn main() { |
| 34 | let netlink = CString::new("udev").unwrap(); |
| 35 | |
| 36 | unsafe { |
| 37 | let udev = udev::udev_new(); |
| 38 | |
| 39 | if !udev.is_null() { |
| 40 | let monitor = udev::udev_monitor_new_from_netlink(udev, netlink.as_ptr()); |
| 41 | |
| 42 | if !monitor.is_null() { |
| 43 | listen(monitor); |
| 44 | udev::udev_monitor_unref(monitor); |
| 45 | } |
| 46 | |
| 47 | udev::udev_unref(udev); |
| 48 | } |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | unsafe fn listen(monitor: *mut udev::udev_monitor) { |
| 53 | udev::udev_monitor_ref(monitor); |
| 54 | |
| 55 | udev::udev_monitor_enable_receiving(monitor); |
| 56 | |
| 57 | let fd = udev::udev_monitor_get_fd(monitor); |
| 58 | let mut fds = vec!(PollFd { fd: fd, events: POLLIN, revents: 0 }); |
| 59 | |
| 60 | while poll((&mut fds[..]).as_mut_ptr(), fds.len() as nfds_t, -1) > 0 { |
| 61 | if fds[0].revents & POLLIN != 0 { |
| 62 | let device = udev::udev_monitor_receive_device(monitor); |
| 63 | print_device(device); |
| 64 | udev::udev_device_unref(device); |
| 65 | } |
| 66 | } |
| 67 | |
| 68 | udev::udev_monitor_unref(monitor); |
| 69 | } |
| 70 | |
| 71 | unsafe fn print_device(device: *mut udev::udev_device) { |
| 72 | let seqnum = udev::udev_device_get_seqnum(device); |
| 73 | let action = unwrap_cstr(udev::udev_device_get_action(device)); |
| 74 | let devpath = unwrap_cstr(udev::udev_device_get_devpath(device)); |
| 75 | let initialized = udev::udev_device_get_is_initialized(device) != 0; |
| 76 | let since = udev::udev_device_get_usec_since_initialized(device); |
| 77 | |
| 78 | println!("{}: [{}] {} (intialized={} usec={})", seqnum, action, devpath, initialized, since); |
| 79 | } |
| 80 | |
| 81 | unsafe fn unwrap_cstr<'a>(ptr: *const c_char) -> &'a str { |
| 82 | if ptr.is_null() { |
| 83 | "" |
| 84 | } |
| 85 | else { |
| 86 | str::from_utf8(CStr::from_ptr(ptr).to_bytes()).unwrap_or("") |
| 87 | } |
| 88 | } |