-
Notifications
You must be signed in to change notification settings - Fork 82
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
3550242
commit 9c53bcd
Showing
1 changed file
with
38 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
package run | ||
|
||
import ( | ||
"context" | ||
"fmt" | ||
"os" | ||
"os/signal" | ||
) | ||
|
||
// SignalHandler returns an actor, i.e. an execute and interrupt func, that | ||
// terminates with SignalError when the process receives one of the provided | ||
// signals, or the parent context is canceled. | ||
func SignalHandler(ctx context.Context, signals ...os.Signal) (execute func() error, interrupt func(error)) { | ||
ctx, cancel := context.WithCancel(ctx) | ||
return func() error { | ||
c := make(chan os.Signal, 1) | ||
signal.Notify(c, signals...) | ||
select { | ||
case sig := <-c: | ||
return SignalError{Signal: sig} | ||
case <-ctx.Done(): | ||
return ctx.Err() | ||
} | ||
}, func(error) { | ||
cancel() | ||
} | ||
} | ||
|
||
// SignalError is returned by the signal handler's execute function | ||
// when it terminates due to a received signal. | ||
type SignalError struct { | ||
Signal os.Signal | ||
} | ||
|
||
// Error implements the error interface. | ||
func (e SignalError) Error() string { | ||
return fmt.Sprintf("received signal %s", e.Signal) | ||
} |