1
0
mirror of https://github.com/go-task/task.git synced 2025-03-17 21:08:01 +02:00

listening for SIGINT and SIGTERM

closes #75
This commit is contained in:
Andrey Nering 2017-11-12 17:39:29 -02:00
parent 57e42af238
commit 71e7cd5808
2 changed files with 25 additions and 3 deletions

View File

@ -1,9 +1,11 @@
package main
import (
"fmt"
"context"
"log"
"os"
"os/signal"
"syscall"
"github.com/go-task/task"
"github.com/go-task/task/internal/args"
@ -37,9 +39,10 @@ Options:
func main() {
log.SetFlags(0)
log.SetOutput(os.Stderr)
pflag.Usage = func() {
fmt.Print(usage)
log.Print(usage)
pflag.PrintDefaults()
}
@ -87,6 +90,8 @@ func main() {
Silent: silent,
Dir: dir,
Context: getSignalContext(),
Stdin: os.Stdin,
Stdout: os.Stdout,
Stderr: os.Stderr,
@ -115,3 +120,15 @@ func main() {
log.Fatal(err)
}
}
func getSignalContext() context.Context {
ch := make(chan os.Signal, 1)
signal.Notify(ch, os.Interrupt, os.Kill, syscall.SIGTERM)
ctx, cancel := context.WithCancel(context.Background())
go func() {
sig := <-ch
log.Printf("task: signal received: %s", sig)
cancel()
}()
return ctx
}

View File

@ -30,6 +30,8 @@ type Executor struct {
Verbose bool
Silent bool
Context context.Context
Stdin io.Reader
Stdout io.Writer
Stderr io.Writer
@ -63,6 +65,9 @@ type Task struct {
// Run runs Task
func (e *Executor) Run(calls ...Call) error {
if e.Context == nil {
e.Context = context.Background()
}
if e.Stdin == nil {
e.Stdin = os.Stdin
}
@ -96,7 +101,7 @@ func (e *Executor) Run(calls ...Call) error {
}
for _, c := range calls {
if err := e.RunTask(context.TODO(), c); err != nil {
if err := e.RunTask(e.Context, c); err != nil {
return err
}
}