Skip to content

Commit

Permalink
feat: add signal handling for graceful shutdown
Browse files Browse the repository at this point in the history
- Add SIGTERM and SIGINT signal handlers
- Spawn dedicated shutdown task
- Wait for shutdown completion before exit
- Add informative logs for shutdown process
  • Loading branch information
aljen committed Dec 7, 2024
1 parent c9b9439 commit 0cf19cc
Showing 1 changed file with 24 additions and 0 deletions.
24 changes: 24 additions & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,31 @@ async fn main() {

async fn run(config: RelayConfig) -> Result<(), Box<dyn std::error::Error>> {
let relay = Arc::new(ModbusRelay::new(config)?);

let relay_clone = Arc::clone(&relay);

let shutdown_task = tokio::spawn(async move {
let mut sigterm = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
.expect("Failed to create SIGTERM signal handler");
let mut sigint = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::interrupt())
.expect("Failed to create SIGINT signal handler");
tokio::select! {
_ = sigterm.recv() => info!("Received SIGTERM"),
_ = sigint.recv() => info!("Received SIGINT"),
}

if let Err(e) = relay_clone.shutdown().await {
error!("Error during shutdown: {}", e);
}
});

relay.run().await?;

info!("Waiting for shutdown to complete...");

shutdown_task.await?;

info!("Modbus Relay stopped");

Ok(())
}

0 comments on commit 0cf19cc

Please sign in to comment.