dourong6054 2017-05-11 23:47
浏览 12
已采纳

在golang中打开带有超时的PE文件

I want to try open a PE file with a timeout in Go. To achieve this, I am using anonymous function while channeling out the file pointer and error. I use the select clause with a timeout case to enforce the timeout as shown below.

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{...}
}

This code works fine for my use case. However, this may lead to resource leakage if the file takes too long to open. How can I prevent this? Is there a better way to enforce timeout on opening the PE file?

  • 写回答

1条回答 默认 最新

  • douluanji8752 2017-05-12 11:13
    关注

    If you have a done channel that's passed to the anonymous func, you can use it to send a signal that you've ended early.

    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 { ... }
        }
    }
    

    When the done channel is closed you will always be able to read the zero value. So your anonymous func won't leak. There's also a struct fileResponse that is scoped to only the function to simplify passing multiple values back from the go routine

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器