Skip to main content

sal_process/
screen.rs

1use crate::run_command;
2use anyhow::Result;
3use std::fs;
4
5/// Executes a command in a new screen session.
6///
7/// # Arguments
8///
9/// * `name` - The name of the screen session.
10/// * `cmd` - The command to execute.
11///
12/// # Returns
13///
14/// * `Result<()>` - Ok if the command was executed successfully, otherwise an error.
15pub fn new(name: &str, cmd: &str) -> Result<()> {
16    let script_path = format!("/tmp/cmd_{}.sh", name);
17    let mut script_content = String::new();
18
19    if !cmd.starts_with("#!") {
20        script_content.push_str("#!/bin/bash\n");
21    }
22
23    script_content.push_str("set -e\n");
24    script_content.push_str(cmd);
25
26    fs::write(&script_path, script_content)?;
27    fs::set_permissions(
28        &script_path,
29        std::os::unix::fs::PermissionsExt::from_mode(0o755),
30    )?;
31
32    let screen_cmd = format!("screen -d -m -S {} {}", name, script_path);
33    run_command(&screen_cmd)?;
34
35    Ok(())
36}
37
38/// Kills a screen session.
39///
40/// # Arguments
41///
42/// * `name` - The name of the screen session to kill.
43///
44/// # Returns
45///
46/// * `Result<()>` - Ok if the session was killed successfully, otherwise an error.
47pub fn kill(name: &str) -> Result<()> {
48    let cmd = format!("screen -S {} -X quit", name);
49    run_command(&cmd)?;
50    std::thread::sleep(std::time::Duration::from_millis(500));
51    Ok(())
52}