Go语言-信号os.Interrupt和信号syscall.SIGTERM的应用
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Go语言-信号os.Interrupt和信号syscall.SIGTERM的应用相关的知识,希望对你有一定的参考价值。
实例
package main
import(
"fmt"
"os"
"os/signal"
"sync"
"syscall"
"time"
)
func worker(stop <-chan bool) {
for {
select {
case <-stop:
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 <-chan bool) {
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(<-sigs)
}
运行结果
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
以上是关于Go语言-信号os.Interrupt和信号syscall.SIGTERM的应用的主要内容,如果未能解决你的问题,请参考以下文章
Linux C语言无名信号量与有名信号量(无名使用 <semaphore.h>,有名信号量<sys/sem.h>)
Linux C语言无名信号量与有名信号量(无名使用 <semaphore.h>,有名信号量<sys/sem.h>)