I write a piece of code which will get a Segmentation fault
. I am not sure whether it is a bug of Boost Coroutine or my code below:
#include <string>
#include <functional>
#include <vector>
#include <fstream>
#include <boost/coroutine/coroutine.hpp>
using namespace std;
template <class T>
using C = boost::coroutines::coroutine<T()>;
string foo(C<string>::caller_type & yield,
std::string fn, int cnt) {
std::ifstream f(fn);
// f.close();
int local_cnt = 0;
while(local_cnt < cnt) {
string l;
getline(f, l);
local_cnt ++;
yield(l);
}
f.close();
}
int main(int argc, char *argv[])
{
vector<C<string> > result;
for(int i = 0; i < 8192; ++i) {
C<string> obj(bind(foo, std::placeholders::_1, "test.txt", 3)); // line I
result.push_back(std::move(obj)); // line J
}
return 0;
}
test.txt
is very large so it will never get the eof before segfault occurring. I use 1.55 of Boost and there are some observation:
- seg-error occured in
line I
- If I delete or move
f.close()
before yield clause, seg-error disappeared. - If I delete
line J
in the code, seg-error disappeared. - If I use a smaller number in stead of
8192
(say 512), seg-error disappeared.
What's the problem here?
"Too many open files" - you exceed the max number of open file descriptors
the seg fault will happen inside the ifstream (does not throw) check ulimit -n cat /proc/sys/fs/file-max sysctl