rust 有没有办法避免使用'时雄::select!'宏?

t3irkdon  于 2023-02-08  发布在  其他
关注(0)|答案(1)|浏览(174)

我使用下面的代码(来自here)来处理正常关机:

use tokio::signal;

pub async fn shutdown_signal() {
    let ctrl_c = async {
        signal::ctrl_c()
            .await
            .expect("failed to install Ctrl+C handler");
    };

    #[cfg(unix)]
    let terminate = async {
        signal::unix::signal(signal::unix::SignalKind::terminate())
            .expect("failed to install signal handler")
            .recv()
            .await;
    };

    #[cfg(not(unix))]
    let terminate = std::future::pending::<()>();

    tokio::select! {
        _ = ctrl_c => {},
        _ = terminate => {},
    }

    tracing::info!("signal received, starting graceful shutdown...");
}

有没有办法避免使用tokio::select!宏?

xuo3flqw

xuo3flqw1#

您可以使用futures 's select()

use tokio::signal;

pub async fn shutdown_signal() {
    let ctrl_c = async {
        signal::ctrl_c()
            .await
            .expect("failed to install Ctrl+C handler");
    };

    #[cfg(unix)]
    let terminate = async {
        signal::unix::signal(signal::unix::SignalKind::terminate())
            .expect("failed to install signal handler")
            .recv()
            .await;
    };

    #[cfg(not(unix))]
    let terminate = std::future::pending::<()>();
    
    tokio::pin!(ctrl_c, terminate);

    futures::future::select(ctrl_c, terminate).await;

    tracing::info!("signal received, starting graceful shutdown...");
}

相关问题