-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaio.c
More file actions
70 lines (61 loc) · 1.57 KB
/
aio.c
File metadata and controls
70 lines (61 loc) · 1.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/* This is free and unencumbered software released into the public domain.
* Refer to LICENSE.txt in this directory. */
/* Simple asynchronous I/O example using libaio. */
#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <libaio.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
static void
handle_io_error(int r, const char *s)
{
if (r < 0)
{
errno = -r;
perror(s);
exit(EXIT_FAILURE);
}
}
int
main(int argc, char **argv)
{
if (argc != 2)
{
fprintf(stderr, "Usage: %s FILENAME\n", argv[0]);
return EXIT_FAILURE;
}
int fd = open(argv[1], O_RDONLY);
if (fd < 0)
{
perror(argv[1]);
return EXIT_FAILURE;
}
io_context_t ctx;
memset(&ctx, 0, sizeof ctx);
handle_io_error(io_setup(1, &ctx), "io_setup");
char buf[4096];
struct iocb cb;
memset(&cb, 0, sizeof cb);
cb.aio_fildes = fd;
cb.aio_lio_opcode = IO_CMD_PREAD;
cb.aio_reqprio = 0;
cb.u.c.buf = buf;
cb.u.c.nbytes = sizeof buf;
cb.u.c.offset = 0;
struct iocb *cbs = &cb;
handle_io_error(io_submit(ctx, 1, &cbs), "io_submit");
/* Wait for debugger to attach. */
printf("pid=%d: press any key to wait for read of %zu bytes from fd %d...\n",
getpid(), sizeof buf, fd);
fflush(stdout);
getchar();
struct io_event event;
handle_io_error(io_getevents(ctx, 1, 1, &event, NULL), "io_getevents");
assert(event.obj == &cb);
handle_io_error(io_destroy(ctx), "io_destroy");
close(fd);
return EXIT_SUCCESS;
}