1 use nix::poll::{EventFlags, poll, PollFd};
2 use nix::unistd::{write, pipe, close};
3
4 #[test]
test_poll()5 fn test_poll() {
6 let (r, w) = pipe().unwrap();
7 let mut fds = [PollFd::new(r, EventFlags::POLLIN)];
8
9 // Poll an idle pipe. Should timeout
10 let nfds = poll(&mut fds, 100).unwrap();
11 assert_eq!(nfds, 0);
12 assert!(!fds[0].revents().unwrap().contains(EventFlags::POLLIN));
13
14 write(w, b".").unwrap();
15
16 // Poll a readable pipe. Should return an event.
17 let nfds = poll(&mut fds, 100).unwrap();
18 assert_eq!(nfds, 1);
19 assert!(fds[0].revents().unwrap().contains(EventFlags::POLLIN));
20 }
21
22 #[test]
test_poll_debug()23 fn test_poll_debug() {
24 assert_eq!(format!("{:?}", PollFd::new(0, EventFlags::empty())),
25 "PollFd { fd: 0, events: (empty), revents: (empty) }");
26 assert_eq!(format!("{:?}", PollFd::new(1, EventFlags::POLLIN)),
27 "PollFd { fd: 1, events: POLLIN, revents: (empty) }");
28
29 // Testing revents requires doing some I/O
30 let (r, w) = pipe().unwrap();
31 let mut fds = [PollFd::new(r, EventFlags::POLLIN)];
32 write(w, b" ").unwrap();
33 close(w).unwrap();
34 poll(&mut fds, -1).unwrap();
35 assert_eq!(format!("{:?}", fds[0]),
36 format!("PollFd {{ fd: {}, events: POLLIN, revents: POLLIN | POLLHUP }}", r));
37 close(r).unwrap();
38 }
39
40 // ppoll(2) is the same as poll except for how it handles timeouts and signals.
41 // Repeating the test for poll(2) should be sufficient to check that our
42 // bindings are correct.
43 #[cfg(any(target_os = "android",
44 target_os = "dragonfly",
45 target_os = "freebsd",
46 target_os = "linux"))]
47 #[test]
test_ppoll()48 fn test_ppoll() {
49 use nix::poll::ppoll;
50 use nix::sys::signal::SigSet;
51 use nix::sys::time::{TimeSpec, TimeValLike};
52
53 let timeout = TimeSpec::milliseconds(1);
54 let (r, w) = pipe().unwrap();
55 let mut fds = [PollFd::new(r, EventFlags::POLLIN)];
56
57 // Poll an idle pipe. Should timeout
58 let nfds = ppoll(&mut fds, timeout, SigSet::empty()).unwrap();
59 assert_eq!(nfds, 0);
60 assert!(!fds[0].revents().unwrap().contains(EventFlags::POLLIN));
61
62 write(w, b".").unwrap();
63
64 // Poll a readable pipe. Should return an event.
65 let nfds = ppoll(&mut fds, timeout, SigSet::empty()).unwrap();
66 assert_eq!(nfds, 1);
67 assert!(fds[0].revents().unwrap().contains(EventFlags::POLLIN));
68 }
69