linux 异步file I/O操作示例:
Core dump
1 #include <sys/types.h> 2 #include <aio.h> 3 #include <fcntl.h> 4 #include <errno.h> 5 #include <iostream> 6 7 using namespace std; 8 9 const int SIZE_TO_READ = 100; 10 11 int main() 12 { 13 // open the file 14 int file = open("blah.txt", O_RDONLY, 0); 15 16 if (file == -1) 17 { 18 cout << "Unable to open file!" << endl; 19 return 1; 20 } 21 22 // create the buffer 23 char* buffer = new char[SIZE_TO_READ]; 24 25 // create the control block structure 26 aiocb cb; 27 28 memset(&cb, 0, sizeof(aiocb)); 29 cb.aio_nbytes = SIZE_TO_READ; 30 cb.aio_fildes = file; 31 cb.aio_offset = 0; 32 cb.aio_buf = buffer; 33 34 // read! 35 if (aio_read(&cb) == -1) 36 { 37 cout << "Unable to create request!" << endl; 38 close(file); 39 } 40 41 cout << "Request enqueued!" << endl; 42 43 // wait until the request has finished 44 while(aio_error(&cb) == EINPROGRESS) 45 { 46 cout << "Working..." << endl; 47 } 48 49 // success? 50 int numBytes = aio_return(&cb); 51 52 if (numBytes != -1) 53 cout << "Success!" << endl; 54 else 55 cout << "Error!" << endl; 56 57 // now clean up 58 delete[] buffer; 59 close(file); 60 61 return 0; 62 }
To compile this code you'll most likely need to link to some external library. On Linux use -lrt, and on OSX it's -lc.
参考: