-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaio_queue.c
More file actions
81 lines (79 loc) · 2.09 KB
/
Copy pathaio_queue.c
File metadata and controls
81 lines (79 loc) · 2.09 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
71
72
73
74
75
76
77
78
79
80
81
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>
#include <aio.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#define NREQ 4
#define BUFSZ 4096
int main(int argc, char **argv)
{
if (argc < 2) {
fprintf(stderr, "usage: %s file\n", argv[0]);
return 1;
}
const char *path = argv[1];
int fd = open(path, O_RDONLY);
if (fd < 0) {
perror("open");
return 1;
}
struct aiocb cbs[NREQ];
char bufs[NREQ][BUFSZ];
off_t offset = 0;
int inflight = 0;
for (int i = 0; i < NREQ; i++) {
memset(&cbs[i], 0, sizeof(struct aiocb));
cbs[i].aio_fildes = fd;
cbs[i].aio_buf = bufs[i];
cbs[i].aio_nbytes = BUFSZ;
cbs[i].aio_offset = offset;
if (aio_read(&cbs[i]) < 0) {
perror("aio_read");
close(fd);
return 1;
}
inflight++;
offset += BUFSZ;
}
while (inflight > 0) {
const struct aiocb *list[NREQ];
for (int i = 0; i < NREQ; i++) {
list[i] = &cbs[i];
}
int r = aio_suspend(list, NREQ, NULL);
if (r < 0 && errno != EINTR) {
perror("aio_suspend");
break;
}
for (int i = 0; i < NREQ; i++) {
int err = aio_error(&cbs[i]);
if (err == EINPROGRESS) continue;
if (err != 0 && err != ECANCELED) {
fprintf(stderr, "aio_error: %s\n", strerror(err));
inflight--;
cbs[i].aio_fildes = -1;
continue;
}
ssize_t n = aio_return(&cbs[i]);
if (n <= 0) {
inflight--;
cbs[i].aio_fildes = -1;
continue;
}
write(STDOUT_FILENO, bufs[i], n);
cbs[i].aio_offset = offset;
cbs[i].aio_nbytes = BUFSZ;
if (aio_read(&cbs[i]) < 0) {
inflight--;
cbs[i].aio_fildes = -1;
} else {
offset += BUFSZ;
}
}
}
close(fd);
return 0;
}