syd 3.58.0

rock-solid application kernel
Documentation
//
// Syd: rock-solid application kernel
// src/utils/syd-tty.rs: Print the controlling terminal of the given process.
//
// Copyright (c) 2024, 2025, 2026 Ali Polatel <alip@chesswob.org>
//
// SPDX-License-Identifier: GPL-3.0

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};

// Set global allocator to GrapheneOS allocator.
#[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()?;

    // Configure syd::proc.
    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(())
}