1 use nix::{
2 errno::Errno,
3 poll::{poll, PollFd, PollFlags, PollTimeout},
4 unistd::{pipe, write},
5 };
6 use std::os::unix::io::{AsFd, BorrowedFd};
7
8 macro_rules! loop_while_eintr {
9 ($poll_expr: expr) => {
10 loop {
11 match $poll_expr {
12 Ok(nfds) => break nfds,
13 Err(Errno::EINTR) => (),
14 Err(e) => panic!("{}", e),
15 }
16 }
17 };
18 }
19
20 #[test]
test_poll()21 fn test_poll() {
22 let (r, w) = pipe().unwrap();
23 let mut fds = [PollFd::new(r.as_fd(), PollFlags::POLLIN)];
24
25 // Poll an idle pipe. Should timeout
26 let nfds = loop_while_eintr!(poll(&mut fds, PollTimeout::from(100u8)));
27 assert_eq!(nfds, 0);
28 assert!(!fds[0].revents().unwrap().contains(PollFlags::POLLIN));
29
30 write(&w, b".").unwrap();
31
32 // Poll a readable pipe. Should return an event.
33 let nfds = poll(&mut fds, PollTimeout::from(100u8)).unwrap();
34 assert_eq!(nfds, 1);
35 assert!(fds[0].revents().unwrap().contains(PollFlags::POLLIN));
36 }
37
38 // ppoll(2) is the same as poll except for how it handles timeouts and signals.
39 // Repeating the test for poll(2) should be sufficient to check that our
40 // bindings are correct.
41 #[cfg(any(linux_android, freebsdlike))]
42 #[test]
test_ppoll()43 fn test_ppoll() {
44 use nix::poll::ppoll;
45 use nix::sys::signal::SigSet;
46 use nix::sys::time::{TimeSpec, TimeValLike};
47
48 let timeout = TimeSpec::milliseconds(1);
49 let (r, w) = pipe().unwrap();
50 let mut fds = [PollFd::new(r.as_fd(), PollFlags::POLLIN)];
51
52 // Poll an idle pipe. Should timeout
53 let sigset = SigSet::empty();
54 let nfds = loop_while_eintr!(ppoll(&mut fds, Some(timeout), Some(sigset)));
55 assert_eq!(nfds, 0);
56 assert!(!fds[0].revents().unwrap().contains(PollFlags::POLLIN));
57
58 write(&w, b".").unwrap();
59
60 // Poll a readable pipe. Should return an event.
61 let nfds = ppoll(&mut fds, Some(timeout), None).unwrap();
62 assert_eq!(nfds, 1);
63 assert!(fds[0].revents().unwrap().contains(PollFlags::POLLIN));
64 }
65
66 #[test]
test_pollfd_events()67 fn test_pollfd_events() {
68 let fd_zero = unsafe { BorrowedFd::borrow_raw(0) };
69 let mut pfd = PollFd::new(fd_zero.as_fd(), PollFlags::POLLIN);
70 assert_eq!(pfd.events(), PollFlags::POLLIN);
71 pfd.set_events(PollFlags::POLLOUT);
72 assert_eq!(pfd.events(), PollFlags::POLLOUT);
73 }
74