如何优雅地关闭Tokio运行时以响应SIGTERM?

hed*_*017 5 asynchronous future shutdown rust rust-tokio

我有一个main函数,我在其中创建一个Tokio运行时并在其上运行两个期货.

use tokio;

fn main() {
    let mut runtime = tokio::runtime::Runtime::new().unwrap();

    runtime.spawn(MyMegaFutureNumberOne {});
    runtime.spawn(MyMegaFutureNumberTwo {});

    // Some code to 'join' them after receiving an OS signal
}
Run Code Online (Sandbox Code Playgroud)

我如何收到SIGTERM,等待所有未完成的任务NotReady并退出应用程序?

Ali*_*yhl 10

对于 Tokio 版本 1.xy,Tokio 官方教程有一个关于此主题的页面:Graceful shutdown


Sta*_*eur 6

处理信号很棘手,而且解释如何处理所有可能的情况会过于宽泛.信号的实现不是跨平台的标准,所以我的答案是针对Linux的.如果想要更加跨平台,请sigaction结合使用POSIX功能pause; 这将为您提供更多控制权.

实现你想要的一种方法是使用tokio_signal crate来捕获信号,如下所示:(doc example)

extern crate futures;
extern crate tokio;
extern crate tokio_signal;

use futures::prelude::*;
use futures::Stream;
use std::time::{Duration, Instant};
use tokio_signal::unix::{Signal, SIGINT, SIGTERM};

fn main() -> Result<(), Box<::std::error::Error>> {
    let mut runtime = tokio::runtime::Runtime::new()?;

    let sigint = Signal::new(SIGINT).flatten_stream();
    let sigterm = Signal::new(SIGTERM).flatten_stream();

    let stream = sigint.select(sigterm);

    let deadline = tokio::timer::Delay::new(Instant::now() + Duration::from_secs(5))
        .map(|()| println!("5 seconds are over"))
        .map_err(|e| eprintln!("Failed to wait: {}", e));

    runtime.spawn(deadline);

    let (item, _rest) = runtime
        .block_on_all(stream.into_future())
        .map_err(|_| "failed to wait for signals")?;

    let item = item.ok_or("received no signal")?;
    if item == SIGINT {
        println!("received SIGINT");
    } else {
        assert_eq!(item, SIGTERM);
        println!("received SIGTERM");
    }

    Ok(())
}
Run Code Online (Sandbox Code Playgroud)

该程序将等待所有当前任务完成,并将捕获所选信号.这似乎不适用于Windows,因为它会立即关闭程序.