github.com/operator-framework/operator-lifecycle-manager@v0.30.0/pkg/lib/signals/signals.go (about)

     1  package signals
     2  
     3  import (
     4  	"context"
     5  	"os"
     6  	"os/signal"
     7  	"sync"
     8  	"syscall"
     9  )
    10  
    11  var (
    12  	shutdownSignals = []os.Signal{os.Interrupt, syscall.SIGTERM}
    13  	signalCtx       context.Context
    14  	cancel          context.CancelFunc
    15  	once            sync.Once
    16  )
    17  
    18  // Context returns a Context registered to close on SIGTERM and SIGINT.
    19  // If a second signal is caught, the program is terminated with exit code 1.
    20  func Context() context.Context {
    21  	once.Do(func() {
    22  		c := make(chan os.Signal, 2)
    23  		signal.Notify(c, shutdownSignals...)
    24  		signalCtx, cancel = context.WithCancel(context.Background())
    25  		go func() {
    26  			<-c
    27  			cancel()
    28  
    29  			select {
    30  			case <-signalCtx.Done():
    31  			case <-c:
    32  				os.Exit(1) // second signal. Exit directly.
    33  			}
    34  		}()
    35  	})
    36  
    37  	return signalCtx
    38  }