您的位置:首页 > 运维架构 > Linux

关于异步IO使用的一个例子

2011-01-14 17:20 956 查看
#include <errno.h>

#include <stdio.h>

#include <fcntl.h>

#include <unistd.h>

#include <string.h>

#include <stdlib.h>

#include <sys/stat.h>

#include <sys/types.h>

#include <libaio.h>

int main()

{

io_context_t ctx;

unsigned nr_events = 10;

memset(&ctx, 0, sizeof(ctx));

int errcode = io_setup(nr_events, &ctx);

if (errcode == 0)

printf("io_setup success\n");

else

printf("io_setup error: :%d:%s\n", errcode, strerror(-errcode));

int fd = open("direct.txt", O_CREAT|O_DIRECT|O_WRONLY, S_IRWXU|S_IRWXG|S_IROTH);

printf("open: %s\n", strerror(errno));

char * buf;

errcode = posix_memalign((void**)&buf, sysconf(_SC_PAGESIZE), sysconf(_SC_PAGESIZE));

printf("posix_memalign: %s\n", strerror(errcode));

strcpy(buf, "hello xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");

struct iocb *iocbpp = (struct iocb *)malloc(sizeof(struct iocb));

memset(iocbpp, 0, sizeof(struct iocb));

iocbpp[0].data = buf;

iocbpp[0].aio_lio_opcode = IO_CMD_PWRITE;

iocbpp[0].aio_reqprio = 0;

iocbpp[0].aio_fildes = fd;

iocbpp[0].u.c.buf = buf;

iocbpp[0].u.c.nbytes = sysconf(_SC_PAGESIZE);

iocbpp[0].u.c.offset = 0;

int n = io_submit(ctx, 1, &iocbpp);

printf("==io_submit==: %d:\n", n);

struct io_event events[10];

struct timespec timeout = {1, 100};

//n = io_getevents(ctx, 1, 10, events, &timeout);

//printf("io_getevents: %d:\n", n);

close(fd);

io_destroy(ctx);

return 0;

}

编译方法:gcc -0 myaio myaio.c -laio -D_GNU_SOURCE
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息