github.com/ssdev-go/moby@v17.12.1-ce-rc2+incompatible/pkg/signal/signal.go (about)

     1  // Package signal provides helper functions for dealing with signals across
     2  // various operating systems.
     3  package signal
     4  
     5  import (
     6  	"fmt"
     7  	"os"
     8  	"os/signal"
     9  	"strconv"
    10  	"strings"
    11  	"syscall"
    12  )
    13  
    14  // CatchAll catches all signals and relays them to the specified channel.
    15  func CatchAll(sigc chan os.Signal) {
    16  	handledSigs := []os.Signal{}
    17  	for _, s := range SignalMap {
    18  		handledSigs = append(handledSigs, s)
    19  	}
    20  	signal.Notify(sigc, handledSigs...)
    21  }
    22  
    23  // StopCatch stops catching the signals and closes the specified channel.
    24  func StopCatch(sigc chan os.Signal) {
    25  	signal.Stop(sigc)
    26  	close(sigc)
    27  }
    28  
    29  // ParseSignal translates a string to a valid syscall signal.
    30  // It returns an error if the signal map doesn't include the given signal.
    31  func ParseSignal(rawSignal string) (syscall.Signal, error) {
    32  	s, err := strconv.Atoi(rawSignal)
    33  	if err == nil {
    34  		if s == 0 {
    35  			return -1, fmt.Errorf("Invalid signal: %s", rawSignal)
    36  		}
    37  		return syscall.Signal(s), nil
    38  	}
    39  	signal, ok := SignalMap[strings.TrimPrefix(strings.ToUpper(rawSignal), "SIG")]
    40  	if !ok {
    41  		return -1, fmt.Errorf("Invalid signal: %s", rawSignal)
    42  	}
    43  	return signal, nil
    44  }
    45  
    46  // ValidSignalForPlatform returns true if a signal is valid on the platform
    47  func ValidSignalForPlatform(sig syscall.Signal) bool {
    48  	for _, v := range SignalMap {
    49  		if v == sig {
    50  			return true
    51  		}
    52  	}
    53  	return false
    54  }