Why child process not awaking from sleep

Hello Rustaceans! I'm trying to write some Rust program but encountered some mysterious problem.

The following program runs well in normal user, but when running it with sudo, the forked child process gets killed.

use nix::unistd::{fork, ForkResult, self};
use tempfile::tempdir;
use std::{fs::OpenOptions, io::{Write, Read}, thread::sleep, time::Duration};

fn main() {
    let tmp_dir = tempdir().unwrap();
    let fifo_path = tmp_dir.path().join("myfifo.pipe");

    // Use fifo for communication between parent and child
    unistd::mkfifo(&fifo_path, nix::sys::stat::Mode::S_IRWXU).unwrap();
    match unsafe{ fork() } {
        Ok(ForkResult::Parent { .. }) => {
            println!("in parent");
            // open fifo to send message
            let mut fifo = OpenOptions::new().write(true).open(&fifo_path).unwrap();
            fifo.write(b"good to go").unwrap();
            println!("parent ended at {:?}, message sent", std::time::Instant::now());
        Ok(ForkResult::Child) => {
            println!("in child");
            // open fifo to receive message
            let mut fifo = OpenOptions::new().read(true).open(&fifo_path).unwrap();
            let mut content = String::new();
            fifo.read_to_string(&mut content).unwrap();
            println!("start sleep");
            sleep(Duration::new(3, 0));
            println!("child ended at {:?}, received: {}", std::time::Instant::now(), content);
        Err(_) => println!("Fork failed"),

I want the program works with sudo

Don't finish the main process that sudo runs before child has time to finish.
It is same whatever language you use.

sudo bash -c "echo start; bash -c 'sleep 1; echo child' & disown; echo end;"

To persist after sudo you need to start programs using the OS service manager (multiple ways) and they won't have access to terminal.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.