Master of Linux 2周前
使用perror();即可知道具体错误原因,我的是open file too many,是因为很多文件打开使用后没有关闭
-------------------------------------------------------------------------------------------------------------------------------------------------
错误原因没找到,找了个替代方法,希望大佬能指点一下
linux平台C++程序,涉及到了对一个文件频繁写入操作,在实际运行中发现,前n次写入均正常,到了第n次后突发段错误。n是个随机值。
简化后的代码如下
FILE * file = NULL;
FILE * get_file(){
if(file == NULL)
{
file = open("abc", "w");
}
return file;
}
char* a = "test txt";
while(true){
fwrite(a, sizeof(a), 1, get_file());
}
在运行过程中,刚开始程序正常运行,文件正常写入,但过一段时间后报段错误。
经过多次gdb调试后的报错。
0x00007ffff6db6f90 in __GI__IO_fwrite (buf=0x7ffff38f5e30, size=16, count=1, fp=0x7fffec001e70) at iofwrite.c:37
37 iofwrite.c: No such file or directory
初步判断是对同一个文件频繁写入造成的(文件过大/缓冲区异常),后对代码进行如下修改,确保一个文件不会写入多次
FILE * file = NULL;
FILE * get_file(){
static int num = 0;
if(file == NULL)
{
file = fopen("abc", "w");
}else
if((num++) % 1000 == 0)
{
fclose(file);
file = fopen("abc", "w");
}
return file;
}
char* a = "test txt";
while(true){
fwrite(a, sizeof(a), 1, get_file());
}
发现在正常运行一段时间后,又出现了上述问题。
类似问题在overstack上也有人提出,但是最后都不了了之。
初步判断是C++标准库的bug。
解决方案是将整个fopen/fwrite体系改成open/write体系