forked from hashicorp/packer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsignal.go
37 lines (34 loc) · 766 Bytes
/
signal.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package command
import (
"context"
"fmt"
"os"
"os/signal"
"syscall"
packersdk "github.com/hashicorp/packer-plugin-sdk/packer"
)
func handleTermInterrupt(ui packersdk.Ui) (context.Context, func()) {
ctx, cancelCtx := context.WithCancel(context.Background())
// Handle interrupts for this build
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, os.Interrupt, syscall.SIGTERM)
cleanup := func() {
cancelCtx()
signal.Stop(sigCh)
close(sigCh)
}
go func() {
select {
case sig := <-sigCh:
if sig == nil {
// context got cancelled and this closed chan probably
// triggered first
return
}
ui.Error(fmt.Sprintf("Cancelling build after receiving %s", sig))
cancelCtx()
case <-ctx.Done():
}
}()
return ctx, cleanup
}