I write a test program with aio, but I find that when the main process of writing data is over, the memory usage of my process never falls down. Can any one give some tips about the problem of my program, or about aio cache?
My program:
#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;
}
The memory usage rises to more than 4G (some times 3G, may change), but the malloc
and free
functions both run 10,000,000 times, so I don't think its memory leak issue.