【问题标题】:Open PE files with timeout in golang在golang中打开PE文件超时
【发布时间】:2017-10-11 03:45:15
【问题描述】:

我想尝试在 Go 中打开一个超时的 PE 文件。为此,我在引导文件指针和错误时使用匿名函数。我使用带有超时情况的 select 子句来强制执行超时,如下所示。

go func() {
    f, e := pe.Open(filePath)
    file <- f
    err <- e
}()

select {
case <-fileOpenTimeout:
    fmt.Printf("ERROR: Opening PE file timed out")
    return
case fileError := <-err:
    if fileError == nil{...}
}

此代码适用于我的用例。但是,如果文件打开时间过长,这可能会导致资源泄漏。我怎样才能防止这种情况?有没有更好的方法来强制打开 PE 文件超时?

【问题讨论】:

    标签: go timeout portable-executable goroutine


    【解决方案1】:

    如果你有一个传递给匿名函数的完成通道,你可以使用它来发送一个你已经提前结束的信号。

    func asd() {
        fileOpenTimeout := time.After(5 * time.Second)
    
        type fileResponse struct {
            file *pe.File
            err error
        }
    
        response := make(chan fileResponse)
        done := make(chan struct{})
    
        go func(done <-chan struct{}) {
            f, e := pe.Open(filePath)
            r := fileResponse{
                file: f,
                err: e,
            }
    
            select {
            case response <- r:
                // do nothing, response sent
            case <-done:
                // clean up
                if f != nil {
                    f.Close()
                }
            }
        }(done)
    
        select {
        case <-fileOpenTimeout:
            fmt.Printf("ERROR: Opening PE file timed out")
            close(done)
            return
        case r := <-response:
            if r.err != nil { ... }
        }
    }
    

    当完成通道关闭时,您将始终能够读取零值。所以你的匿名函数不会泄漏。还有一个 struct fileResponse,它的作用域仅限于函数,以简化从 go 例程传回多个值的过程

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-08
      • 2020-04-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多