Break out of 3rd party goroutine that has an infinite loop

元气小坏坏 提交于 2019-12-11 15:22:33

问题


I'm using this to receive SNMP traps: https://github.com/soniah/gosnmp Now, lets say I want to programmatically break out of the (taken from here):

err := tl.Listen("0.0.0.0:9162")

What are my best approaches to this?

I'm somewhat new to Golang and didnt find a way to break out of a goroutine that I have no way of modifying ("3rd party").

Thanks,


回答1:


Short answer: You can't. There's no way to kill a goroutine (short of killing the entire program) from outside the goroutine.

Long answer: A goroutine can listen for some sort of "terminate" signal (via channels, signals, or any other mechanism). But ultimately, the goroutine must terminate from within.

Looking at the library in your example, it appears this functionality is not provided.




回答2:


Standard https://golang.org/pkg/net/#Conn interface provides special methods SetDeadline (together with SetReadDeadline and SetWriteDeadline) to set a hard connection break time for staled connections. As I see in the source code:

type GoSNMP struct {
    // Conn is net connection to use, typically established using GoSNMP.Connect()
    Conn net.Conn
     ...

    // Timeout is the timeout for the SNMP Query
    Timeout time.Duration
    ...

net.Conn interface is exported - so you may try to get direct access to it to set up a deadline.

type TrapListener struct {
    OnNewTrap func(s *SnmpPacket, u *net.UDPAddr)
    Params    *GoSNMP
    ...
}

In its turn TrapListener exports GoSNMP struct so you may have access to it. Try this:

tl := TrapListener{...}
tl.Params.Conn.SetDeadline(time.Now().Add(1*time.Second))
tl.Listen(...)

However this line disensures me - looks like it doesn't use stored connection and its options:

func (t *TrapListener) Listen(addr string) (err error) {
    ...
    conn, err := net.ListenUDP("udp", udpAddr)
    ....
}

But you may try :)



来源:https://stackoverflow.com/questions/46671181/break-out-of-3rd-party-goroutine-that-has-an-infinite-loop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!