use std::os::fd::BorrowedFd;
use std::time::Duration;
use rustix::event::{PollFd, PollFlags, Timespec, poll};
const INTERVAL: Duration = Duration::from_millis(500);
const HANGUP_STATUS: i32 = 129;
pub(crate) fn watch() {
let Some(terminal) = terminal([rustix::stdio::stdin(), rustix::stdio::stdout()]) else {
return;
};
let _ = std::thread::Builder::new().name("hangup".to_owned()).spawn(move || {
while !hung_up(terminal) {
std::thread::sleep(INTERVAL);
}
let _ = ratatui::try_restore();
crate::pi::link::remove_entry();
std::process::exit(HANGUP_STATUS);
});
}
fn terminal(fds: [BorrowedFd<'_>; 2]) -> Option<BorrowedFd<'_>> {
fds.into_iter().find(|fd| rustix::termios::isatty(fd))
}
fn hung_up(fd: BorrowedFd<'_>) -> bool {
let mut fds = [PollFd::new(&fd, PollFlags::IN)];
let now = Timespec { tv_sec: 0, tv_nsec: 0 };
poll(&mut fds, Some(&now)).is_ok() && fds.iter().any(|entry| entry.revents().contains(PollFlags::HUP))
}
#[cfg(test)]
mod tests {
#![allow(clippy::expect_used, reason = "tests assert by panicking")]
use std::os::fd::{AsFd as _, OwnedFd};
use rustix::fs::{Mode, OFlags};
use rustix::pty::{OpenptFlags, grantpt, openpt, ptsname, unlockpt};
use super::*;
fn pty() -> (OwnedFd, OwnedFd) {
let controller = openpt(OpenptFlags::RDWR | OpenptFlags::NOCTTY).expect("openpt");
rustix::io::fcntl_setfd(&controller, rustix::io::FdFlags::CLOEXEC).expect("cloexec");
grantpt(&controller).expect("grantpt");
unlockpt(&controller).expect("unlockpt");
let name = ptsname(&controller, Vec::new()).expect("ptsname");
let tty =
rustix::fs::open(name.as_c_str(), OFlags::RDWR | OFlags::NOCTTY | OFlags::CLOEXEC, Mode::empty())
.expect("open");
(controller, tty)
}
#[test]
fn a_terminal_reads_as_hung_up_only_after_its_other_end_closes() {
let (controller, tty) = pty();
assert!(!hung_up(tty.as_fd()));
drop(controller);
let deadline = std::time::Instant::now() + Duration::from_secs(5);
while !hung_up(tty.as_fd()) && std::time::Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(20));
}
assert!(hung_up(tty.as_fd()));
}
#[test]
fn piped_stdin_is_passed_over_for_the_terminal() {
let (reader, writer) = std::io::pipe().expect("pipe");
drop(writer);
let (_controller, tty) = pty();
assert!(hung_up(reader.as_fd()), "a finished pipe reports a hang-up");
let watched = terminal([reader.as_fd(), tty.as_fd()]).expect("a terminal");
assert!(!hung_up(watched));
}
}