I have an http server (launched using http.Handle
) and I would like to do some operations.
How can I do that (on linux) ? Is it possible to do those operations in case of a ctrl-C ?
I'm not familiar with unix signals so the answer may be trivial.
Using kostix answer, I built this code (now adapted to Go1) to catch the interrupt signal and do some operations before exiting :
go func() {
sigchan := make(chan os.Signal)
signal.Notify(sigchan, os.Interrupt)
<-sigchan
log.Println("Program killed !")
// do last actions and wait for all write operations to end
os.Exit(0)
}()
// start main program tasks
You can subscribe to the TERM and INT signals using the signal package. But note that these signals are only sent when the process is killed explicitly; normal exit (initiated by the process itself) does not involve any sort of signals. I think for normal exit just do something in the main routine (which supposedly should spawn worker goroutines and then wait on them).
Read man 7 signal
for more general info on POSIX signals.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With