如何使RUST在后台正常运行并进行守护进程?

问题描述 投票:-1回答:1

这是我想要实现的

root> ./webserver start   // Does not block the terminal after startup, runs in the background and the process is guarded
root> 

我当前的实现逻辑:

在后台运行的逻辑
 use std::process::Command;
use std::thread;
use std::env;
use std::time::Duration;

fn main() {
    let args: Vec<String> = env::args().collect();
    if args.len() == 2 {
        if &args[1] == "start" {
            // Main process start child process
            let child = Command::new(&args[0])
                .spawn().expect("Child process failed to start.");
            println!("child pid: {}", child.id());
            // Main process exit
        }
    } else {Is there any more elegant approach? Looking forward to your reply
        // Main business logic
        run webserver
    }
}

这样,生锈将在后台运行,而不会阻塞终端,但是在后台由生锈打印的信息仍将显示在终端上,并且当前的生锈程序将在退出终端时退出]]进程守护程序逻辑

我的想法是监视系统的退出信号,而不处理退出请求

SIGHUP       1          /* Hangup (POSIX).  */                  
SIGINT       2          /* Interrupt (ANSI).  */                       
SIGQUIT      3          /* Quit (POSIX).  */                        
SIGTERM      15         /* Termination (ANSI).  */               

代码:

use signal_hook::{iterator::Signals, SIGHUP,SIGINT,SIGQUIT,SIGTERM};
use std::{thread, time::Duration};
pub fn process_daemon() {
    let signals = match Signals::new(&[SIGHUP,SIGINT,SIGQUIT,SIGTERM]) {
        Ok(t) => t,
        Err(e) => panic!(e),
    };Is there any more elegant approach? Looking forward to your reply

    thread::spawn(move || {
        for sig in signals.forever() {
            println!("Received signal {:?}", sig);
        }
    });

    thread::sleep(Duration::from_secs(2));
}

还有其他更优雅的方法吗?期待您的回复。

这是我想要获得的root> ./webserver start //启动后不阻塞终端,在后台运行并且进程受root保护。我当前的实现逻辑:...

service rust daemon
1个回答
2
投票

TLDR:如果您真的希望您的流程像服务一样工作(并且never

© www.soinside.com 2019 - 2024. All rights reserved.