aio.c (1596B)
1 #include <aio.h> 2 #include <sys/stat.h> 3 #include <fcntl.h> 4 5 #include <errno.h> 6 #include <stdlib.h> 7 #include <stddef.h> 8 #include <stdio.h> 9 #include <string.h> 10 11 int main(int argc, char* argv[]) 12 { 13 ++argv; 14 --argc; 15 16 unsigned int width = 0; 17 18 char* bufs[argc]; 19 struct aiocb aios[argc]; 20 struct aiocb* liop[argc]; 21 22 for (int i = 0; i < argc; ++i) 23 { 24 struct aiocb* a = aios + i; 25 int f = open(argv[i], O_RDONLY); 26 struct stat s; 27 28 fstat(f, &s); 29 30 if (!S_ISREG(s.st_mode)) 31 { 32 printf("%s not a regular file!\n", argv[i]); 33 exit(1); 34 } 35 36 bufs[i] = malloc(s.st_size); 37 38 a->aio_fildes = f; 39 a->aio_lio_opcode = LIO_READ; 40 a->aio_offset = 0; 41 a->aio_buf = bufs[i]; 42 a->aio_nbytes = (size_t)s.st_size; 43 a->aio_sigevent.sigev_notify = SIGEV_NONE; 44 a->aio_reqprio = 0; 45 46 liop[i] = a; 47 48 unsigned len = strlen(argv[i]); 49 if (len > width) 50 width = len; 51 } 52 53 lio_listio(LIO_NOWAIT, liop, argc, NULL); 54 55 int cycles = 0; 56 57 while (argc) 58 { 59 printf("cycle %u:\n", ++cycles); 60 aio_suspend((struct aiocb const* const*)liop, argc, NULL); 61 62 for (int i = 0; i < argc; ) 63 { 64 switch(aio_error(liop[i])) 65 { 66 case EINPROGRESS: 67 ++i; 68 continue; 69 70 case 0: 71 72 break; 73 default: 74 exit(1); 75 } 76 77 size_t size = aio_return(liop[i]); 78 char* str = bufs[i], *end = str + size; 79 unsigned lines = 0; 80 81 while (str < end) 82 if (*str++ == '\n') 83 ++lines; 84 85 free(bufs[i]); 86 printf(" %*s: %6lu bytes, %4u lines\n", width, argv[i], size, lines); 87 if (i >= --argc) 88 break; 89 90 bufs[i] = bufs[argc]; 91 argv[i] = argv[argc]; 92 liop[i] = liop[argc]; 93 } 94 } 95 96 return 0; 97 } 98