我有一个守护进程(在 Ubuntu Server 16.04 上运行,使用 g++ -std=c++11
编译)依赖于两个函数来知道目录是否存在以及目录是否为空:
bool DirectoryExists ( const char* path ) {
if( path == NULL ) return false;
DIR *d;
d = opendir(path);
if (d){
closedir(d);
return true;
}
return false;
}
bool isEmpty(const char* path) {
int n = 0;
//Directory scan
DIR *d;
struct dirent *dir;
d = opendir(path);
if (d){
while ((dir = readdir(d)) != NULL){
if(dir->d_name[0] == '.')continue;
if(++n > 0) break;
}
closedir(d);
}
else{
return false;
}
if (n == 0) //Directory Empty
return true;
else
return false;
}
问题是,在守护程序工作一两天后,这些函数开始不断返回 FALSE
(两者),而它们应该返回 TRUE
。我怀疑 DIR *
指针没有正确关闭,但我无法修复它。
我在这里做错了什么?
编辑:
在我的代码的某些部分,我使用 DirectoryExists
来检查删除的目录是否真的消失了,或者它是否仍然存在。检查完成后,errno
设置为“No such file or directory”,这是正确的,但我不知道这是否是我的问题的根源。
system("rm -rf " + fullpath);
if(DirectoryExists(std::string(fullpath).c_str())){
syslog(LOG_ERR, "ERROR: Directory %s couldn't be removed", fullpath.c_str());
return false;
}
编辑 2:
正如我所怀疑的,当这些函数开始失败时,errno 被设置为“太多打开的文件”
最佳答案
我的猜测是违规行是包含 std::string(fullpath).c_str()
的行:
if(DirectoryExists(std::string(fullpath).c_str())) {
...
}
您正在使用一个在函数进入之前就被销毁的临时文件。幸运的是,c_str()
指向的内存似乎包含您想要的字符串,但在某些时候情况不再如此(可能是因为内存碎片增加了内存分配器重用的压力内存)。
关于c++ - 几天后 DIR 函数返回 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38054020/