【问题标题】:Break out of 3rd party goroutine that has an infinite loop突破具有无限循环的第 3 方 goroutine
【发布时间】:2018-03-22 02:57:11
【问题描述】:

我正在使用它来接收 SNMP 陷阱:https://github.com/soniah/gosnmp 现在,假设我想以编程方式突破(取自here):

错误 := tl.Listen("0.0.0.0:9162")

我最好的方法是什么?

我对 Golang 有点陌生,但没有找到摆脱我无法修改的 goroutine 的方法(“第 3 方”)。

谢谢,

【问题讨论】:

标签: go goroutine


【解决方案1】:

简短的回答:你不能。没有办法从 goroutine 之外杀死一个 goroutine(除了杀死整个程序)。

长答案:goroutine 可以监听某种“终止”信号(通过通道、信号或任何其他机制)。但最终,goroutine 必须从内部终止。

查看示例中的库,似乎未提供此功能。

【讨论】:

  • 认为我需要添加它。谢谢!
【解决方案2】:

标准https://golang.org/pkg/net/#Conn 接口提供了特殊方法SetDeadline(连同SetReadDeadlineSetWriteDeadline)来为陈旧的连接设置硬连接中断时间。正如我在source 代码中看到的那样:

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 接口已导出 - 因此您可以尝试直接访问它以设置截止日期。

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

反过来TrapListener 导出GoSNMP 结构,因此您可以访问它。试试这个:

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

但是 this line 让我不放心 - 看起来它不使用存储连接及其选项:

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

但你可以试试:)

【讨论】:

    猜你喜欢
    • 2013-03-08
    • 2012-04-02
    • 2014-03-11
    • 1970-01-01
    • 1970-01-01
    • 2018-11-05
    • 2013-09-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多