Windows overlapped I/O detailed

Source: Internet
Author: User
Tags readfile

Http://www.cnblogs.com/skyofbitbit/p/3650140.html

I/O device processing must allow the main program to stop and wait for I/O completion,
On this issue have

Method One: Use another thread for I/O.                This plan works, but it's troublesome. That is, CreateThread (...).      ; Create a child thread to do something else. Readfile (^ ......) ; blocking way to read data.

Method Two: Use overlapped I/O.
Overlapped I/O is a WIN32 technology that you can ask the operating system to transmit data to you and notify you when it is delivered. This technique allows your program to continue to process transactions while I/O is in progress. In fact, the operating system internally is the thread I/O complete overlapped I/O. You can get all the benefits of the thread without paying any painful price

How to use overlapped I/O:

Specify overlapped mode when I/O operation is performed
Using CreateFile (), specify its 6th parameter as file_flag_overlapped,
is to be prepared to use overlapped to construct or open the file;
If overlapped is used, the 5th parameter of the ReadFile (), WriteFile () must provide a pointer to the
Point to a overlapped structure. Overlapped is used to record some relevant information about the file currently being manipulated.

Function: Read 300 bytes from 1500 bits of the specified file
int main ()
{
BOOL RC;
HANDLE hfile;
DWORD Numread;
overlapped overlap;
Char buf[512];
Char szpath= "c:\\xxxx\xxxx";
hfile = CreateFile (szpath,
Generic_read,
file_share_read| File_share_write,
Null
Open_existing,
file_flag_overlapped,//Open file with overlapped
Null
);

The

//overlapped structure is actually initialized to 0
    memset (&overlap, 0, sizeof (overlap));
   // The specified file location is 1500;
    overlap. Offset = 1500;
    
    rc = ReadFile (HFILE,BUF,300,&NUMREAD,&OVERLAP);
   //Because it is a overlapped operation, ReadFile returns (false) immediately after the read file request is placed in the read queue, but does not wait until the file is read to return (true)
    if (RC)
    {

....... The data is available here.
      //file is really read, RC is true
      // Or when the data is placed in the cache, or the operating system thinks it can get the data very quickly, RC is true
   }
    Else
     {
        if (GetLastError () = error_io_pending)
         {//When the error is error_io_pending, that means the operation of the read file is still in progress
         //Wait until the file is read
            WaitForSingleObject (hfile, INFINITE);
            rc = GetOverlappedResult (hfile,& Overlap,&numread,false); The functionality of the
           //above two statements is equivalent to the functionality of one of the following statements:

One block waits until the data is available to continue below.
GetOverlappedResult (hfile,&overlap,&numread,true);
}
Else
{
There was a mistake.
}
}
CloseHandle (hfile);
return exit_success;
}

In practical work, if you have several operations of the same file,
What to do. We can use the event provided in the overlapped structure to solve the problems encountered above.
Note that the event object you are using must be of a manual type, otherwise, you may have a competitive condition.
int main ()
{
int i;
BOOL RC;
Char szpath= "x:\\xxxx\xxxx";
Open a file in a overlapped way
Ghfile = CreateFile (szpath,
Generic_read,
file_share_read| File_share_write,
Null
Open_existing,
File_flag_overlapped,
Null
);
For (i=0 i<max_requests; i++) REQUESTS have n simultaneously read files
{
Read the same file in several parts at the same time in overlapped mode
Notice how the Queuerequest function is shipped, read 16,384 blocks at a time
Queuerequest (i, i*16384, read_size);
}
Wait for all operations to end;
Implied condition: When an operation completes, its corresponding event object is activated
WaitForMultipleObjects (max_requests, ghevents, TRUE, INFINITE);
Finishing operations
for (i=0; i<max_requests; i++)
{
DWORD Dwnumread;
rc = GetOverlappedResult (
Ghfile,
&goverlapped[i],
&dwnumread,
FALSE
);
CloseHandle (goverlapped[i].hevent);
}
CloseHandle (Ghfile);
return exit_success;
}

When the read operation is complete, the goverlapped[nindex].hevent system is fired
int queuerequest (int nindex, DWORD dwlocation, DWORD Dwamount)
{
Construct an Event object of manual type
Ghevents[nindex] = CreateEvent (null, TRUE, FALSE, NULL);
Place this event object into the overlapped structure
Goverlapped[nindex].hevent = Ghevents[nindex];

Each overlapping object corresponds to an event.
Goverlapped[nindex]. Offset = dwlocation;
For (i=0 i<max_try_count; i++)//try several times.
{
File Ghfile Unique
rc = ReadFile (Ghfile, Gbuffers[nindex],&dwnumread,&goverlapped[nindex]);
if (RC) returns TRUE if the data is read immediately
return TRUE;
Err = GetLastError ();
if (err = = error_io_pending)
{
When the error is error_io_pending, it means the operation of the read file is still in progress.
return TRUE;
}
Handle some recoverable errors
if (err = = Error_invalid_user_buffer | |
Err = = Error_not_enough_quota | |
Err = = error_not_enough_memory)
{
Sleep (50);
continue;//Retry
}
If GetLastError () returns the error that is not listed above, discard
Break
}

return-1;

}

Program Flow:

1:n a user reads each part of a file at the same time, and each user corresponds to an overlapping object and event.

2: Call WaitForMultipleObjects (Max_requests, ghevents, TRUE, INFINITE) function stops blocking when any user's read operation completes. And the event for the user who has completed the read data in ghevents is activated.

3: Call GetOverlappedResult to get the user number that reads the data.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.