Skip to content

Instantly share code, notes, and snippets.

@ollie314
Last active June 26, 2024 08:42
Show Gist options
  • Save ollie314/5a87090b39a3fd05102ef122bdd30540 to your computer and use it in GitHub Desktop.
Save ollie314/5a87090b39a3fd05102ef122bdd30540 to your computer and use it in GitHub Desktop.
Gracefull shutdown memo
# Trap in scripts
# source: https://unix.stackexchange.com/questions/57940/trap-int-term-exit-really-necessary
cleanup() {
echo "Cleaning stuff up..."
exit
}
trap cleanup INT TERM
echo ' --- press ENTER to close --- '
read var
cleanup
# Docker commands
## gracefull stop
docker exec <containerId> stop
# or
docker kill --signal=SIGTERM <containerId>
## gracefull period
docker stop --time <duration> <containerId>
# duration expressed in seconds
# ex: docker stop -t 60 <containerId>
# --time (long option), -t (short option)
// source: https://www.serverlessguru.com/blog/are-you-gracefully-shutting-down-your-containers
package main
import (
"os"
"os/signal"
"syscall"
"time" // or "runtime"
)
func cleanup() {
// close database/server/etc
}
func main() {
c := make(chan os.Signal)
signal.Notify(c, os.Interrupt, syscall.SIGTERM, syscall.SIGINT)
go func() {
<-c
cleanup()
os.Exit(1)
}()
// rest of the app
}
process.once("SIGTERM", () => {
// Handling sigterm
});
process.once("SIGINT", () => {
// handling sigint
});
// source: https://rust-cli.github.io/book/in-depth/signals.html
use signal_hook::{consts::SIGINT, iterator::Signals};
use std::{error::Error, thread, time::Duration};
fn main() -> Result<(), Box<dyn Error>> {
let mut signals = Signals::new(&[SIGINT])?;
thread::spawn(move || {
for sig in signals.forever() {
println!("Received signal {:?}", sig);
}
});
// Following code does the actual work, and can be interrupted by pressing
// Ctrl-C. As an example: Let's wait a few seconds.
thread::sleep(Duration::from_secs(2));
Ok(())
}
// Using tokio
// source: https://blog.logrocket.com/guide-signal-handling-rust/
use tokio::signal::unix::{signal, SignalKind};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut sigint = signal(SignalKind::interrupt())?;
match sigint.recv().await {
Some(()) => println!("Received SIGINT signal"),
None => eprintln!("Stream terminated before receiving SIGINT signal"),
}
for num in 0..10000 {
println!("{}", num)
}
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment