Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

do actions on end of execution

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.

like image 289
Denys Séguret Avatar asked Dec 06 '11 17:12

Denys Séguret


2 Answers

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
like image 90
Denys Séguret Avatar answered Oct 24 '22 10:10

Denys Séguret


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.

like image 45
kostix Avatar answered Oct 24 '22 08:10

kostix