use std::{
io::{stdout, Write},
os::unix::ffi::OsStrExt,
process::ExitCode,
};
use nix::{errno::Errno, fcntl::OFlag, libc::pid_t, unistd::Pid};
use syd::{eprintfln, fd::open_static_proc, printfln, proc::util::proc_tty};
#[cfg(all(
not(target_os = "android"),
not(target_arch = "loongarch64"),
not(target_arch = "riscv64"),
target_page_size_4k,
target_pointer_width = "64"
))]
#[global_allocator]
static GLOBAL: hardened_malloc::HardenedMalloc = hardened_malloc::HardenedMalloc;
syd::main! {
syd::set_sigpipe_dfl()?;
open_static_proc(OFlag::O_PATH)?;
let pid = match std::env::args().nth(1).map(|arg| arg.parse::<pid_t>()) {
Some(Ok(pid)) => Pid::from_raw(pid),
None => Pid::this(),
Some(Err(_)) => {
help()?;
return Ok(ExitCode::SUCCESS);
}
};
match proc_tty(pid) {
Ok(path) => {
let path = path.as_os_str().as_bytes();
stdout().write_all(path)?;
}
Err(errno) => {
eprintfln!("syd-tty: {errno}")?;
return Ok(ExitCode::from(errno as u8));
}
}
Ok(ExitCode::SUCCESS)
}
fn help() -> Result<(), Errno> {
printfln!("Usage: syd-tty [PID]")?;
printfln!("Print the controlling terminal of the given process.")?;
Ok(())
}