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

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

报告相同问题?

悬赏问题

  • ¥30 c#打开word开启修订并实时显示批注
  • ¥15 如何解决ldsc的这条报错/index error
  • ¥15 VS2022+WDK驱动开发环境
  • ¥30 关于#java#的问题,请各位专家解答!
  • ¥30 vue+element根据数据循环生成多个table,如何实现最后一列 平均分合并
  • ¥20 pcf8563时钟芯片不启振
  • ¥20 pip2.40更新pip2.43时报错
  • ¥15 换yum源但仍然用不了httpd
  • ¥50 C# 使用DEVMOD设置打印机首选项
  • ¥15 麒麟V10 arm安装gdal