在golang中打开超时的PE文件
Open PE files with timeout in golang
我想尝试在 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 文件超时?
如果你有一个传递给匿名函数的完成通道,你可以用它来发送一个你已经提前结束的信号。
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 { ... }
}
}
当 done 通道关闭时,您将始终能够读取零值。所以你的匿名函数不会泄露。还有一个 struct fileResponse 的范围仅限于简化从 go 例程传回多个值的函数
我想尝试在 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 文件超时?
如果你有一个传递给匿名函数的完成通道,你可以用它来发送一个你已经提前结束的信号。
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 { ... }
}
}
当 done 通道关闭时,您将始终能够读取零值。所以你的匿名函数不会泄露。还有一个 struct fileResponse 的范围仅限于简化从 go 例程传回多个值的函数