我有一些用于遍历目录的go代码,运行时它失败,并带有panic: fcntl: too many open files
。据我所知,问题是我还没有打开任何文件(也没有可调用.Close()的文件对象)。
package main
import (
"sync"
"io/ioutil"
"path"
)
func walk (cfg config) {
var wg sync.WaitGroup
wg.Add(1)
go processDir(cfg.fromDir, "", &wg, cfg)
wg.Wait()
}
// path, relative path, waitGroup, config
func processDir (pth string, relPth string, wg *sync.WaitGroup, cfg config) {
defer wg.Done()
flInfo, err := ioutil.ReadDir(pth)
if err != nil {
panic(err)
}
for _, f := range flInfo {
var fPath = f.Name()
var isDir = f.IsDir()
if cfg.shouldIgnore(fPath) {
continue
}
wg.Add(1)
var newAbs = path.Join(pth, fPath)
if isDir {
var newRel = path.Join(relPth, fPath)
go processDir(newAbs, newRel, wg, cfg)
} else {
go processFile(newAbs, relPth, wg, cfg)
}
}
}
func processFile (pth string, relPth string, wg *sync.WaitGroup, cfg config) {
defer wg.Done()
// TODO: Process file
}
我想知道,
ioutil.ReadDir()
调用是否打开目录的文件描述符,并且在不限制goroutine数量的情况下,我的程序一次读取了太多目录?这是我第一次使用goroutines,因此对任何指针都表示赞赏。
最佳答案
经过一些调查,我在此答案中使用“计数信号量”模式解决了该问题:
https://stackoverflow.com/a/38825523/7674702
我不确定这是否意味着这个问题是重复的,因为问题非常相似,但并不完全相同。
关于multithreading - Golang中“打开的文件太多”而未打开任何文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60384128/