Go 应用无法捕捉信号

从 linux 上的 kill 发送信号, kill -s 2 <PID>或kill -s 15 <PID>


代码是:


package main


import (

  "fmt"

   "os"

   "os/signal"

)


func main() {

    sigs := make(chan os.Signal, 1)

    done := make(chan bool, 1)

    signal.Notify(sigs)

    go func() {

        sig := <-sigs

        fmt.Println(sig)

    }()

    fmt.Println("waiting")

    <-done

    fmt.Println("exiting")

}

该程序不处理信号,只能CTRL+C运行良好。


蝴蝶不菲
浏览 205回答 1
1回答

鸿蒙传说

func()在收到第一个信号后终止,我认为CTLR+C是您尝试时的第一个信号。当它被包裹在一个循环中时它起作用。package mainimport (&nbsp; "fmt"&nbsp; &nbsp;"os"&nbsp; &nbsp;"os/signal")func main() {&nbsp; &nbsp; sigs := make(chan os.Signal, 1)&nbsp; &nbsp; done := make(chan bool, 1)&nbsp; &nbsp; signal.Notify(sigs)&nbsp; &nbsp; go func() {&nbsp; &nbsp; &nbsp; &nbsp; for {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; sig := <-sigs&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(sig)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }()&nbsp; &nbsp; fmt.Println("waiting")&nbsp; &nbsp; <-done&nbsp; &nbsp; fmt.Println("exiting")}测试;$ kill -15 <pid>$ kill -2 <pid>$ kill -10 <pid>$ kill -1 <pid>$ kill -10 <pid>$ ./signal&nbsp;waitingterminatedinterruptuser defined signal 1hangupuser defined signal 1
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go