The source code is listed below:
#include <stdio.h>#include<stdlib.h>#include<string.h>#include<aio.h>#include<unistd.h>#include<signal.h>#include<sys/stat.h>#include<fcntl.h>Static Char*Membuffer;Static intSfiledesc;Static structsigaction soldsigaction;Static voidMysigquithandler (intSIG) {printf ("Signal quit! the number is:%d\n", SIG);}Static voidMyfilereadcompleteprocedure (intSIG, Siginfo_t *si,void*Ucontext) {printf ("The file length is:%zu, and the content is:%s\n", strlen (Membuffer), membuffer); intStatus =Close (SFILEDESC); if(Status = =0) puts ("File closed successfully!"); Elseprintf ("The error code is:%d\n", status); Free (membuffer); //restores the original SIGUSR1 signal behavior if(Sigaction (SIGUSR1, &soldsigaction, NULL) = =-1) puts ("SIGUSR1 Signal Restore failed!");}intMainvoid){ structSigaction sigaction = {. Sa_flags = Sa_restart,. Sa_handler = &Mysigquithandler}; Sigemptyset (&sigaction.sa_mask); if(Sigaction (Sigquit, &sigaction, NULL) = =-1) {puts ("Signal failed!"); return-1; } sigaction.sa_sigaction= &myfilereadcompleteprocedure; if(Sigaction (SIGUSR1, &sigaction, &soldsigaction) = =-1) {puts ("Signal failed!"); return-1; } Const Char*filepath ="MyFile.txt"; Constmode_t mode = S_IRUSR | S_IWUSR | S_irgrp |S_iroth; Sfiledesc=Open (FilePath, o_rdonly, mode); if(Sfiledesc = =-1) {printf ("The file:%s cannot be opened!\n", FilePath); return-1; } Const LongFilelength = Lseek (Sfiledesc,0, Seek_end); Lseek (Sfiledesc,0, Seek_set); Membuffer= malloc (Filelength +1); Membuffer[filelength]=' /'; structAIOCB Aiobuffer; Aiobuffer.aio_fildes=Sfiledesc; Aiobuffer.aio_offset=0; Aiobuffer.aio_buf=Membuffer; Aiobuffer.aio_nbytes=filelength; Aiobuffer.aio_reqprio=0; Aiobuffer.aio_sigevent= (structsigevent) {. Sigev_notify = sigev_signal,. Sigev_signo = SIGUSR1,. sigev_value.sival_ptr =Membuffer}; Aio_read (&Aiobuffer); GetChar (); return 0;}
Wherein, the above code implementation uses the SIGUSR1 signal to capture the file read completion event, of course, here can also use Sigio signal.
In addition, you must add the-LRT command option when compiling the link, because the RT library contains the underlying API of the system.
Linux reads files asynchronously through AIO