github.com/TrueBlocks/trueblocks-core/src/apps/chifra@v0.0.0-20241022031540-b362680128f7/pkg/sigintTrap/trap.go (about)

     1  // Copyright 2021 The TrueBlocks Authors. All rights reserved.
     2  // Use of this source code is governed by a license that can
     3  // be found in the LICENSE file.
     4  
     5  package sigintTrap
     6  
     7  import (
     8  	"context"
     9  	"os"
    10  	"os/signal"
    11  	"sync"
    12  
    13  	"github.com/TrueBlocks/trueblocks-core/src/apps/chifra/pkg/colors"
    14  )
    15  
    16  var TrapMessage = colors.Yellow + "Ctrl+C. Finishing..." + colors.Off
    17  var sigintMessageOnce sync.Once
    18  
    19  type CleanupFunction func()
    20  
    21  // Enable enables the trap, by blocking control-C. It returns
    22  // a channel that will get a value when user presses ctrl-C.
    23  func Enable(ctx context.Context, cancel context.CancelFunc, cleanUp CleanupFunction) chan os.Signal {
    24  	signals := make(chan os.Signal, 1)
    25  	signal.Notify(signals, os.Interrupt)
    26  
    27  	go func() {
    28  		for {
    29  			select {
    30  			case <-signals:
    31  				sigintMessageOnce.Do(cleanUp)
    32  				if cancel != nil {
    33  					cancel()
    34  				}
    35  				return
    36  			case <-ctx.Done():
    37  				return
    38  			}
    39  		}
    40  	}()
    41  
    42  	return signals
    43  }
    44  
    45  func Disable(channel chan os.Signal) {
    46  	signal.Stop(channel)
    47  }