我用aio写了一个测试程序,但我发现当写入数据的主要过程结束时,我的进程的内存使用量永远不会下降。任何人都可以提供有关我的程序问题或aio缓存的一些提示吗?
我的节目:
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <aio.h>
FILE *db_file;
void aio_completion_handler(sigval_t sigval)
{
int ret;
struct aiocb *pb;
pb = (struct aiocb *)sigval.sival_ptr;
if ((ret = aio_return(pb)) > 0) {}
printf((char*)pb->aio_buf);
free((void*)pb->aio_buf);
free((void*)pb);
}
int write_1000W()
{
for(int i = 0; i < 10000000; ++i)
{
char *buf;
const int BUFLEN = 1024*1024;
struct aiocb *pb;
buf = (char*)malloc(BUFLEN);
bzero((void*)buf, BUFLEN);
pb = (struct aiocb*)malloc(sizeof(struct aiocb));
bzero((void*)pb, sizeof(struct aiocb));
sprintf(buf, "{%d %d %d}\n", i, i, i);
pb->aio_buf = buf;
pb->aio_fildes = fileno(db_file);
pb->aio_nbytes = strlen(buf);
pb->aio_offset = 0;
pb->aio_sigevent.sigev_notify = SIGEV_THREAD;
pb->aio_sigevent._sigev_un._sigev_thread._function = aio_completion_handler;
pb->aio_sigevent._sigev_un._sigev_thread._attribute = NULL;
pb->aio_sigevent.sigev_value.sival_ptr = pb;
if (aio_write(pb) < 0)
{
free(buf);
free(pb);
}
}
}
int main()
{
db_file = fopen ("./1000W.txt", "a+");
if(!db_file)
{
printf("Cannot open file for append.\n");
exit(1);
}
write_1000W();
printf("0000000000000\n");
sleep(300);
return 0;
}
内存使用率上升到4G以上(有些时候3G可能会发生变化),但malloc
和free
函数都运行10,000,000次,所以我不认为它的内存泄漏问题。