Bootstrap

go语言os.exit(1)_Go语言-信号os.Interrupt和信号syscall.SIGTERM的应用

实例

package main

import(

"fmt"

"os"

"os/signal"

"sync"

"syscall"

"time"

)

func worker(stop

for {

select {

case

fmt.Println("exit")

return

default:

fmt.Println("running...")

time.Sleep(3)

}

}

}

func main() {

stop := make(chan bool)

var wg sync.WaitGroup

for i := 0; i < 3; i++ {

wg.Add(1)

go func(stop

defer wg.Done()

worker(stop)

}(stop)

}

waitForSignal()

close(stop)

fmt.Println("stopping all job")

wg.Wait()

}

func waitForSignal() {

sigs := make(chan os.Signal)

signal.Notify(sigs, os.Interrupt)

signal.Notify(sigs, syscall.SIGTERM)

fmt.Println(

}

运行结果

pkill信号syscall.SIGTERM

...

running...

running...

running...

running...

terminated

running...

running...

stopping all job

exit

exit

exit

或者ctrl+c信号os.Interrupt

running...

interrupt

stopping all job

running...

exit

exit

exit

;