如何在golang上获得gocmq中断信号?

时间:2018-05-12 05:03:47

标签: go

**我使用goczmq,但在Windwos上运行服务器时我不会捕获系统中断。为什么呢?**

signal_channel := make(chan os.Signal)
signal.Notify(signal_channel)
go goczmq....
<-signal_channel

1 个答案:

答案 0 :(得分:1)

我做了一个简单的例子,似乎按预期工作。
代码在package main import ( "os" "os/signal" "time" "fmt" ) func main() { fmt.Println( "Started...") signal_channel := make(chan os.Signal) signal.Notify(signal_channel) go func() { // do whatever... time.Sleep(10 *time.Second) }() sig1 := <-signal_channel fmt.Println( "\n\nGot signal: ", sig1 ) fmt.Println( "Done.") }

> go run a.go &
[1] 26515
Started...

>kill -HUP %1

Got signal:  hangup
Done. 

> go run a.go &
[1] 26768
> Started...

kill -USR1 %1

Got signal:  user defined signal 1

go run a.go  // + Press CTRL-Z
Started...
^Z
[1]+  Stopped                 go run a.go

Got signal:  stopped
Done.

另外:

> go run a.go // + Press CTRL-C 
Started...
^C

Got signal:  interrupt
Done.

package main

import (
    "os"
    "os/signal"
    "time"
    "fmt"
)

func main() {

    fmt.Println( "Started...")
    signal_channel := make(chan os.Signal)
    signal.Notify(signal_channel)
    go func() {
        // do whatever...
        sig2 := <-signal_channel
        fmt.Println( "gorutine sig2: ", sig2)
        time.Sleep(10 *time.Second)
    }()

    time.Sleep(10 *time.Second)
    sig1 := <-signal_channel
    fmt.Println( "\n\nGot signal: ", sig1 )

    fmt.Println( "Done.")

}

如果在您的情况下不可见,可能会在gorutine中消耗。 喜欢在:

^Cgorutine sig2:  interrupt

得到:

  

去跑a.go       开始...

response = ""
def reply():
    global response
    response = 'I am good'
    return;

sentence = input('You: ')

if sentence == "How are you?":
    reply()
    global response
print('Bot: ' + response)