github.com/hashicorp/packer@v1.14.3/command/signal.go (about) 1 // Copyright (c) HashiCorp, Inc. 2 // SPDX-License-Identifier: BUSL-1.1 3 4 package command 5 6 import ( 7 "context" 8 "fmt" 9 "os" 10 "os/signal" 11 "syscall" 12 13 packersdk "github.com/hashicorp/packer-plugin-sdk/packer" 14 ) 15 16 func handleTermInterrupt(ui packersdk.Ui) (context.Context, func()) { 17 ctx, cancelCtx := context.WithCancel(context.Background()) 18 // Handle interrupts for this build 19 sigCh := make(chan os.Signal, 1) 20 signal.Notify(sigCh, os.Interrupt, syscall.SIGTERM) 21 cleanup := func() { 22 cancelCtx() 23 signal.Stop(sigCh) 24 close(sigCh) 25 } 26 go func() { 27 select { 28 case sig := <-sigCh: 29 if sig == nil { 30 // context got cancelled and this closed chan probably 31 // triggered first 32 return 33 } 34 ui.Error(fmt.Sprintf("Cancelling build after receiving %s", sig)) 35 cancelCtx() 36 case <-ctx.Done(): 37 } 38 }() 39 return ctx, cleanup 40 }