armybox 0.3.0

A memory-safe #[no_std] BusyBox/Toybox clone in Rust - 299 Unix utilities in ~500KB
Documentation
//! nohup - run a command immune to hangups
//!
//! Run a command immune to hangups, with output to a non-tty.

use crate::io;
use crate::sys;
use crate::applets::get_arg;

/// nohup - run a command immune to hangups
///
/// # Synopsis
/// ```text
/// nohup command [arg...]
/// ```
///
/// # Description
/// Run command immune to hangups. If stdout is a terminal, redirect it
/// to nohup.out. SIGHUP is ignored.
///
/// # Exit Status
/// - 127: Command not found or cannot be executed
/// - Command's exit status otherwise
pub fn nohup(argc: i32, argv: *const *const u8) -> i32 {
    if argc < 2 {
        io::write_str(2, b"nohup: missing operand\n");
        return 1;
    }

    // Ignore SIGHUP
    unsafe {
        libc::signal(libc::SIGHUP, libc::SIG_IGN);
    }

    // Redirect stdout to nohup.out if it's a tty
    if unsafe { libc::isatty(1) } != 0 {
        let fd = io::open(b"nohup.out", libc::O_WRONLY | libc::O_CREAT | libc::O_APPEND, 0o644);
        if fd >= 0 {
            io::dup2(fd, 1);
            io::close(fd);
        }
    }

    let cmd = unsafe { get_arg(argv, 1).unwrap() };
    let mut cmd_buf = [0u8; 4096];
    cmd_buf[..cmd.len()].copy_from_slice(cmd);
    let cmd_ptr = cmd_buf.as_ptr() as *const i8;
    let argv_ptrs = [cmd_ptr, core::ptr::null()];
    unsafe { libc::execv(cmd_ptr, argv_ptrs.as_ptr()) };
    sys::perror(b"exec");
    127
}

#[cfg(test)]
mod tests {
    extern crate std;
    use std::process::Command;
    use std::path::PathBuf;

    fn get_armybox_path() -> PathBuf {
        if let Ok(path) = std::env::var("ARMYBOX_PATH") {
            return PathBuf::from(path);
        }
        let manifest_dir = std::env::var("CARGO_MANIFEST_DIR")
            .map(PathBuf::from)
            .unwrap_or_else(|_| std::env::current_dir().unwrap());
        let release = manifest_dir.join("target/release/armybox");
        if release.exists() { return release; }
        manifest_dir.join("target/debug/armybox")
    }

    #[test]
    fn test_nohup_no_args() {
        let armybox = get_armybox_path();
        if !armybox.exists() { return; }

        let output = Command::new(&armybox)
            .args(["nohup"])
            .output()
            .unwrap();

        assert_eq!(output.status.code(), Some(1));
        let stderr = std::string::String::from_utf8_lossy(&output.stderr);
        assert!(stderr.contains("missing operand"));
    }

    #[test]
    fn test_nohup_with_command() {
        let armybox = get_armybox_path();
        if !armybox.exists() { return; }

        let output = Command::new(&armybox)
            .args(["nohup", "/bin/true"])
            .output()
            .unwrap();

        assert_eq!(output.status.code(), Some(0));
    }
}