do actions on end of execution

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.


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