storj/cmd/storj-sim/cancelable.go

35 lines
597 B
Go
Raw Normal View History

2019-01-24 20:15:10 +00:00
// Copyright (C) 2019 Storj Labs, Inc.
2019-01-02 18:07:49 +00:00
// See LICENSE for copying information.
package main
import (
"context"
"os"
"os/signal"
)
// NewCLIContext creates a context that can be canceled with Ctrl-C.
2019-01-02 18:07:49 +00:00
func NewCLIContext(root context.Context) (context.Context, func()) {
// trap Ctrl+C and call cancel on the context
ctx, cancel := context.WithCancel(root)
signals := make(chan os.Signal, 1)
signal.Notify(signals, os.Interrupt)
2019-01-08 15:24:15 +00:00
stop := func() {
signal.Stop(signals)
cancel()
}
2019-01-02 18:07:49 +00:00
go func() {
select {
case <-signals:
2019-01-08 15:24:15 +00:00
stop()
2019-01-02 18:07:49 +00:00
case <-ctx.Done():
}
}()
2019-01-08 15:24:15 +00:00
return ctx, stop
2019-01-02 18:07:49 +00:00
}