Compare commits

...

2 Commits

Author SHA1 Message Date
19e0392db6 优化内存不足时的日志管理行为 2026-02-02 21:05:10 +08:00
d01219da30 优化日志内存不足时的写入逻辑 2026-02-02 21:04:52 +08:00

View File

@ -9,6 +9,34 @@
#include <fcntl.h>
#include <string.h>
int write_into_block(char *writein,char *org,int *length,int maxlength,char *logname)
{
if(writein == NULL||org == NULL||length == NULL||logname == NULL)
return -1;
if(*length+strlen(org)<maxlength-1)
{
strcpy(&writein[*length],org);
*length +=strlen(org);//栈内存充足
}
else
{
int n = *length + strlen(org) - maxlength;
strncpy(&writein[*length],org,strlen(org)-n);//栈内存不足
writein[maxlength-1] = '\0';
int fd = open(logname,O_CREAT | O_WRONLY | O_APPEND, 0644);
if(fd != -1)
{
write(fd,writein,maxlength);
close(fd);
}
else if(fd == -1)
perror("log:");//仅警告
*length = n;
strcpy(writein,&org[*length]);//剩余部分拷贝
}
return 0;
}
int in_log(logs *log,log_manager *self)
{
if(log == NULL||self == NULL)
@ -102,7 +130,7 @@ int cleanup(log_manager *self)
char failback[MAX_LOG_LENGTH];
logbuf = (char*)malloc(1);
logbuf[0] = '\0';
size_t buf_length,buf_lengthbk = 0;
size_t buf_length = 0,buf_lengthbk = 0;
int fd;
while(loc->next !=NULL)
{
@ -120,7 +148,8 @@ int cleanup(log_manager *self)
close(fd);
}
free(logbufbk);
logbuf = failback;//降级策略,堆空间不足时,使用预分配栈空间,保留最后一条日志
logbuf = failback;//降级策略,堆空间不足时,使用预分配栈空间
buf_length = 0;
}
if(logbuf != failback){
buf_lengthbk = buf_length;
@ -129,7 +158,7 @@ int cleanup(log_manager *self)
}
else
{
buf_length = MAX_LOG_LENGTH;
write_into_block(logbuf,tobeclean->log,&buf_length,MAX_LOG_LENGTH,"log.txt");
}
free(tobeclean);
}
@ -151,14 +180,11 @@ int cleanup(log_manager *self)
}
}
else{
strcpy(logbuf,loc->log);
buf_length = strlen(logbuf);
}
if(logbuf == failback&&buf_length>MAX_LOG_LENGTH)
logbuf[MAX_LOG_LENGTH-1] = '\0';
else{
logbuf[buf_length] = '\0';
write_into_block(logbuf,loc->log,&buf_length,MAX_LOG_LENGTH,"log.txt");
}
logbuf[buf_length] = '\0';
free(loc);
fd = open("log.txt",O_CREAT | O_WRONLY | O_APPEND, 0644);