tcrm-task 0.4.2

Task execution unit for TCRM project
Documentation
/// Send a signal to a process by process ID (Unix).
///
/// Uses the nix::sys::signal::kill() function to send any signal to the specified process.
///
/// # Arguments
///
/// * `pid` - The process ID to send the signal to
/// * `signal` - The signal to send
///
/// # Returns
///
/// - `Ok(())` if the signal was sent successfully
/// - `Err(std::io::Error)` if sending the signal failed
///
/// # Example
/// ```rust,no_run
/// use tcrm_task::tasks::process::action::signal::send_signal;
/// use nix::sys::signal::Signal;
/// let pid = 1234;
/// send_signal(pid, Signal::SIGUSR1).unwrap();
/// ```
#[cfg(unix)]
pub fn send_signal(pid: u32, signal: nix::sys::signal::Signal) -> Result<(), std::io::Error> {
    use nix::errno::Errno;
    use nix::sys::signal::kill;
    use nix::unistd::Pid;

    // Check for invalid pid
    if pid == 0 {
        return Err(std::io::Error::new(
            std::io::ErrorKind::InvalidInput,
            "Invalid PID: 0",
        ));
    }

    // Convert pid to i32
    let pid_i32 = match i32::try_from(pid) {
        Ok(p) => p,
        Err(_) => {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidInput,
                format!("PID {} is too large for this system", pid),
            ));
        }
    };

    match kill(Pid::from_raw(pid_i32), signal) {
        Ok(_) => Ok(()),
        Err(e) => match e {
            Errno::ESRCH => Err(std::io::Error::new(
                std::io::ErrorKind::NotFound,
                format!("Process with PID {} does not exist", pid),
            )),
            Errno::EPERM => Err(std::io::Error::new(
                std::io::ErrorKind::PermissionDenied,
                format!("Permission denied to send signal to PID {}", pid),
            )),
            _ => Err(std::io::Error::new(
                std::io::ErrorKind::Other,
                format!("Failed to send signal to PID {}: {}", pid, e),
            )),
        },
    }
}