agones.dev/agones@v1.53.0/pkg/util/signals/signals.go (about)

     1  // Copyright 2017 Google LLC All Rights Reserved.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  // Package signals contains utilities for managing process signals,
    16  // particularly around stopping processes
    17  package signals
    18  
    19  import (
    20  	"context"
    21  	"os"
    22  	"os/signal"
    23  	"syscall"
    24  )
    25  
    26  // NewSigKillContext returns a Context that cancels when os.Interrupt or os.Kill is received
    27  // along with a stop function that can be used to unregister the signal behavior.
    28  func NewSigKillContext() (context.Context, context.CancelFunc) {
    29  	return signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
    30  }
    31  
    32  // NewSigTermHandler creates a channel to listen to SIGTERM and runs the handle function
    33  func NewSigTermHandler(handle func()) {
    34  	c := make(chan os.Signal, 1)
    35  	signal.Notify(c, syscall.SIGTERM, syscall.SIGINT)
    36  
    37  	go func() {
    38  		<-c
    39  		handle()
    40  	}()
    41  }