初次使用linux下的異步I/O
1
#include <stdio.h>
2
#include <stdlib.h>
3
#include <aio.h>
4
#include <errno.h>
5
6
7
int main(int argc, char *argv[])
8

{
9
10
int fd, ret;
11
struct aiocb my_aiocb;
12
13
fd = open( "file.txt", O_RDONLY );
14
if (fd < 0) perror("open");
15
16
/**//* Zero out the aiocb structure (recommended) */
17
bzero( (char *)&my_aiocb, sizeof(struct aiocb) );
18
19
/**//* Allocate a data buffer for the aiocb request */
20
my_aiocb.aio_buf = malloc(BUFSIZE+1);
21
if (!my_aiocb.aio_buf) perror("malloc");
22
23
/**//* Initialize the necessary fields in the aiocb */
24
my_aiocb.aio_fildes = fd;
25
my_aiocb.aio_nbytes = BUFSIZE;
26
my_aiocb.aio_offset = 0;
27
28
ret = aio_read( &my_aiocb );
29
if (ret < 0) perror("aio_read");
30
31
while ( aio_error( &my_aiocb ) == EINPROGRESS ) ;
32
33
if ((ret = aio_return( &my_iocb )) > 0)
{
34
printf("%s\n", my_aiocb.aio_buf);
35
/**//* got ret bytes on the read */
36
} else
{
37
/**//* read failed, consult errno */
38
}
39
40
41
}

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

g++ test.cpp -lrt