Chapter 10: Synchronous device I/O and asynchronous device I/O

Source: Internet
Author: User

 

As there are too many notes in Chapter 10, I will post the previous notes first.

1. functions used to open various devices

Device

Function used to open a device

File

Createfile (pszname is the path name or UNC path name)

Directory

Createfile (pszname is the path name or UNC path name ). if you specify the file_flag_backup_semantics flag when calling createfile, Windows allows us to open a directory. open the directory so that we can change the properties of the directory (hidden, normal ...) and its Timestamp

Logical Disk Drive

Createfile (pszname is "\. \ x") Windows allows us to open a logical disk drive, where X is the drive letter, open the drive is we can format the drive or check the drive media size

Physical disk drive

Createfile (pszname is "\\. \ physicaldrivex "). in this case, Windows allows us to open a physical disk drive, where X is the physical drive number. open the physical drive so that we can directly access the hard disk partition table. opening a physical drive may pose a potential danger. Wrong writing to the device may cause the operating system file to be unable to access the disk content.

Serial Port

Createfile (pszname is "comx ")

Parallel Port

Createfile (pszname is "lptx ")

Mail slot Server

Createmailslot (pszname is "\. \ Mailslot \ mailslotname"

Mail slot Client

Createfile (pszname is "\ servername \ mailsolt \ mailsoltname"

Named Pipe Server

Createnamedpipe (pszname is "\. \ PIPE \ pipename ")

Named Pipe Client

Createflies (pszname is "\. \ servername \ PIPE \ pipename ")

Anonymous Pipeline

Createpipe is used to open the server and client

Socket

Socket, accept or acceptex

Console

Crateconsolescreenbuffer or getstdhandle

Set the baud rate of the serial port:

Bool setcommconfig (

Handle hcommdev,

Lpcommconfig PCC,

DWORD dwsize );

You can set a timeout value while waiting for reading.

Bool setmailslotinfo (

Handle hmailslot,

DWORD dwreadtimeout );

If there is a device handle, you can call getfiletype to identify the device type:

DWORD getfiletype (handle hdevice );

Value

Description

File_type_unknown

The specified file is of unknown type.

File_type_disk

The specified file is a disk.

File_type_char

The specified file is a character file, generally a parallel device or Console

File_type_pipe

The specified file is a named pipeline or an anonymous pipeline.

Detailed description of createfile:

Handle createfile (

Pctstr pszname, // indicates the device type, or an instance of the device

DWORD dwdesiredaccess, // The method used to transmit data to the device. The specific values are as follows:

DWORD dw1_mode, // used to specify the sharing privilege of a device. When we still open a device, this parameter can // control the call of other createfiles and how the device can be opened.

Psecurity_attributes PSA ,//

DWORD dwcreationdisposition,

DWORD dwflagsandattributes,

Handle hfiletemplate); // indicates an opened file handle.

Dwdesiredaccess value:

Value

Description

0

We do not want to read data from the device or write data to the device. If you want to change the configuration of the device (such as the timestamp of the Knowledge modification file), you can input 0

Generic_read

Allow read-only access to devices

Generic_write

Allow write-only access to the device.

Generic_write |

Generic_read

Allows the device to perform read/write operations. Because this flag allows us to freely exchange data with the device, it is the most commonly used

Dwsharemode value:

Value

Description

0

Requires exclusive access to the device. If the device is enabled, createfile fails to be called.

File_pai_read

If other kernel objects need to use this device, we require that they do not modify the data of the device. if the device has been opened in write or exclusive mode, the createfile call will fail. if the device is successfully enabled, subsequent createfile calls with the generic_write access flag will fail.

File_pai_write

Same as above

File_pai_read |

File_pai_write

If other kernel objects use this device, we do not care if they read data from the device or write data to the device. if the device has been opened exclusively, createfile fails to be called. if the device is successfully enabled, the subsequent requests require exclusive read access, and exclusive write access or exclusive read access will fail.

File_pai_delete

When operating on a file, we do not care whether the file is logically deleted or moved. in Windows, the system marks the file as to be deleted, and then deletes it when all opened handles of the file are closed.

Dwcreationdisposition value:

Value

Description

Create_new

Tells createfile to create a new file. If the file already exists, the call fails.

Create_always

Tell createfile whether a file with the same name exists or not to create a new file. If a file with the same name already exists, this function will overwrite the original file.

Open_existing

Open an existing file or device. If the file or device does not exist, the call will fail.

Open_always

Open an existing file. If the file exists, the function will open it directly. If the file does not exist, the function will create a new file.

Truncate_existing

Open an existing file and cut the file size to 0 bytes. If the file does not exist, the call fails.

If you want to use createfile to open a device other than a file, you must pass open_existing to the dwcreationdisposition parameter.

Dwflagsandattribute two purposes:

1. Allow us to set some labels for fine-tuning communication with devices;

2. if the device is a file, we can also attribute the device file.

Most of these communication signs are signals used to tell the system how to access the device.

Communication mark:

1. cache mark:

File_flag_no_buffering: indicates that no data cache is used for file access.

However, certain rules must be followed during use:

◆ When accessing a file, the offset must be exactly an integer multiple of the disk volume's sector size (you can use the getdiskfreespace function to determine the disk volume's sector size)

◆ The number of bytes for reading/writing files must be exactly an integer multiple of the slice size.

◆ Make sure that the starting address in the cached process address space is exactly an integer multiple of the slice size.

File_flag_sequential_scan and file_flag_random_access are ignored only when we allow the system to cache file data.

If the former is specified, the system will think that we will access the file in sequence (a large amount of data is read at a time). If this is not required, you can specify the next flag.

File_flag_write_through: Do not cache file write operations to reduce the possibility of data loss. At this time, the system will directly Write File modifications to the disk. However, the file data will be saved in the internal cache.

2. Other logos:

File_flag_delete_on_close is often used together with the file_attribute_temporary attribute, indicating that the application creates a temporary file, writes data to the file, reads data from the file, and closes the file. when the file is closed, the system automatically deletes the file.

File_flag_backup_semantics: to ensure that the process attempting to open a file or create a file has the required access privileges, the system usually performs a security check. This flag is generally used for backup and recovery software.

File_flag_posix_semantics: indicates that the file name is case sensitive.

File_flag_open_reparse_point informs the system to ignore the file's re-resolution attribute. This flag is not recommended.

File_flag_open_no_recall: tells the system not to restore the file content from offline storage to online storage.

File_flag_overlapped: indicates that the system wants to access the device asynchronously.

Dwflagsandattritemplate flag: this parameter is ignored unless we are creating a new file and the parameter we passed to hfiletemplate is null.

Flag

Description

File_attribute_archive

The file is an archive file. The application uses this flag to mark the file as to be backed up or to be deleted. This flag is set by default.

File_attribute_encrypted

Files are encrypted.

File_attribute_hidden

The file is hidden. It does not appear in the common directory list.

File_attribute_normal

The file has no other attributes. This flag is valid only when it is used separately.

File_attribute_not_content_indexed

The Content Indexing Service does not index files.

File_attribute_offline

Although the file exists, the file content has been transferred to offline storage. This flag is useful to Hierarchical Storage Systems.

File_attribute_readonly

The file is read-only. The application can read the file, but cannot write or delete the file.

File_attribute_system

Files are part of the operating system or are exclusively called by the system.

File_attribute_temporary

The file data only takes a while. To minimize the access time, the file system tries its best to save the file data in the memory instead of on the disk.

Dwfiletemplate: if a file handle is identified, createfile will completely ignore the dwflagsandattribute parameter and use the attributes used by hfiletemplate instead (this must be a file opened with the generic_read flag ). if you open an existing file, this parameter is ignored.

If the function is successfully called, a file or device handle is returned. If the function fails, invalid_handle_value is returned.

2. Get the file size:

Bool getfilesizeex (

Handle hfile, // handle

Plarge_integer plifilesize); // Return Value

The structure is defined as follows: (in fact, this structure has been used before when we used the timer kernel object)

// Signed

Typedef union _ large_integer

{

Struct

{

DWORD lowpart;

Long highpart;

};

Longlong quadpart;

} Large_integer, * plarge_integer;

// Unsigned

Typedef union _ ularge_integer

{

Struct

{

DWORD lowpart;

DWORD highpart;

};

Ulonglong quadpart;

} Ularge_integer, * pularge_integer;

Another function used to obtain the physical size of a file is as follows:

DWORD getcompressedfilesize (

Pctstr pszfilename ,//

Pdword pdwfilesizehigh );

The difference between the two functions: the former is to obtain the logical size, and the latter is to return the physical size (the actual physical size occupied ).

3. Explanation of common functions:

◆ File reading:

Bool readfile (

Handle hfile, // file handle

Lpvoid lpbuffer, // buffer pointer

DWORD nnumberofbytestoread, // The number of bytes to read

Lpdword lpnumberofbytesread, // the actual number of bytes used

Lpoverlapped); // generally set null

This function will produce an error if it sets lpnumberofbytesread to null. Usage:

Handle hfile = createfile (strpath,

Generic_read,

0,

Null,

Open_existing,

File_attribute_readonly,

Null );

If (hfile = invalid_handle_value)

{

MessageBox ("file opening failed ");

}

Else

{

Char ch [10000];

DWORD dwnumbyte;

Memset (CH, 0,100 );

Readfile (hfile, CH, 9999, & dwnumbyte, null );

Ch [dwnumbyte-1] = '\ 0 ';

// The ch content is the read content.

}

◆ Random File Access (change the file pointer associated with the file kernel object ).

Bool setfilepointerex (

Handle hfile,

Large_integer lidistancetomove, // number of bytes to move the pointer

Plarge_integer plinewfilepointer, // return the new pointer Value

DWORD dwmovemethod); // how to explain plinewfilepointer. The specific values are as follows:

Value

Description

File_begin

The file pointer of the object will be set to the value specified by the lidistancetomove parameter. Here lidistancetomove is interpreted as an unsigned 64-bit value.

File_current

The file pointer of the object will be added to lidistancetomove. To move the pointer backward, you can interpret lidistancetomove as a signed 64-bit value.

File_end

The file pointer of the file object is set to the logical size of the file plus the lidistancetomove parameter. To move the pointer backward, you can interpret lidistancetomove as a signed 64-bit value.

Some noteworthy facts:

● Set the file pointer value to an operation that exceeds the current size of the file. unless data is written to the file at this location or setendoffile is called, this will not increase the actual size of the file on the disk.

● If the file operated by setfilepointerex is opened with the file_flag_no_buffering flag, the file pointer can only be set to an integer multiple of the sector size.

● Windows does not provide a getfilepointerex function. We can use the following code to obtain the value of the current pointer:

Large_integer licurrentposition = {0 };

Setfilepointerex (hfile, licurrentposition, & licurrentposition, file_current );

◆ Set the end of the file

Bool setendoffile (

Handle hfile );

Usually, when you close a file, the system is responsible for setting the end Of the file. This function truncates the file size or increases the file size based on the current position of the file pointer of the file object.

// The following Code sets the object size to 1024 bytes.

Handle hfile = createfile (...);

Large_integer lidistancetomove;

Lidistancetomove. quadpart = 1024;

Setfilepointerex (hfile, lidistancetomove, null, file_begin );

Setendoffile (hfile );

4. Several common functions:

■ Write functions:

For example, if file_flag_overlapped is specified when the file is opened, a special structure must be referenced with this parameter. The structure defines a previous asynchronous read operation. Otherwise, the parameter should be set to null.

Bool writefile (

Handle hfile,

Const void * pvbuffer, // Cache

DWORD nnumbytestowrite, // number of bytes written to the device

Pdword pdwnumbytes, // number of bytes actually written to the data.

Overlapped * poverlapped );

If the two functions are successful, true is returned. Otherwise, false is returned. The two functions must have corresponding permissions.

Similarly, if we pass null to pdwnumbytes when calling this function, an exception will occur.

■ Force refresh the data so that the data is written to the device in the cache.

Bool flushfilebuffers (handle hfile );

If the call is successful, true is returned. Otherwise, flase is returned.

5. functions used to synchronize I/O are easy, but they will block any operation from the same thread (that is, the thread that sends an I/O request.

Vista provides some major features: If the console stops responding when synchronizing I/O, you can press Ctrl + C to get control and continue using it. in addition, the new vista provides a Cancel button for the open and save file dialog box. If the program does not respond for a period of time, you can click the cancel button.

Vista provides a function that allows us to cancel an unfinished synchronous I/O Request from a given thread:

Bool cancelsynchronousio (handle hthread); // The parameter indicates the thread to be suspended because of waiting for I/O.

This handle must be created with the thread_terminate access permission. if the specified thread is suspended because the synchronization I/O operation is completed, cancelsynchronousio will be awakened by the suspended thread, and the Operations attempted by the thread will also fail. (getlasterror returns error_operation_aborted), and returns true to the caller.

If the thread is not suspended because it is waiting for the response from the device when cancelsynchronousio is called, the function returns flase (getlasterror returns error_not_found ).\

Note: The above are all cases where the driver supports cancellation.

6. asynchronous Operation: when performing an asynchronous operation, we need to pass the file_flag_overlapped flag to the dwflagsandattried parameter of the createfile function to open the device. This flag also tells us that we want to access the device asynchronously. (this is to pass null to the pdwnumbyte function of readfile and writefile ).

Overlapped structure:

Typedef struct _ overlapped

{

DWORD internal; // [out] error code

DWORD internalhigh; // [out] number of bytes transferred

DWORD offset; // [in] low 32-bit file offset

DWORD offsethigh; // [in] High 32-bit file offset

Handle hevent; // [in] event handle or data

} Overlapped, * lpoverlapped;

Parameters:

Offset and offsethigh: they constitute a 64-bit offset, which indicates where to start I/O operations when accessing files. note that asynchronous operations will ignore file pointers. non-file devices will ignore offset and offsethigh -- we will initialize both Members to 0. otherwise, the I/O request will fail.

Hevent: This member will be used when I/O is used to complete the port. When the I/O notification function can be used, we can use this member as needed.

Internal: Save the error code of the processed I/O Request. once an asynchronous I/O request is sent, the device driver immediately sets internal to stauts_pending, indicating no error. because the operation has not started yet. WINBASE. hasoverlappediocompleted defined in H allows us to check whether an asynchronous I/O operation has been completed. if it is still in the waiting status, false is returned; otherwise, true is returned.

# Define hasoverlappediocompleted (poverlapped )\

(Poverlapped)-> internal )! = Status_pening)

Internalhigh: When asynchronous I/O is complete, this member is used to save the number of transmitted bytes.

Asynchronous device I/O considerations:

■ The device driver does not have to process the I/O requests in the queue in the first-in-first-out mode.

■ Check errors in the correct way

If getlasterror returns error_io_pending, it indicates that the I/O request has been successfully added to the queue and will be completed later.

The returned value is error_invalid_user_buffer or error_not_enough_memory, indicating that the non-Paging buffer pool is full.

The returned value is error_not_enough_quota. Some devices require locking the storage page where our data cache is located, so that when I/O is waiting for processing, the data will not be called out of memory. if fiile_flag_no_buffering is used, if the lock fails at this time, error_not_enough_quota is returned.

Before an asynchronous I/O request is completed, the data cache and overlapped structure used for sending an I/O request cannot be moved or destroyed.

7. Sometimes women needs the device driver to cancel a device I/O request that has been added to the queue before processing. Windows provides a method to achieve this purpose.

■ We can call cancelio to cancel all I/O Requests added to the queue by the thread marked by the given handle (unless the handle has an I/O completion port associated with it ):

Bool cancelio (handle hfile );

■ We can disable the device handle to cancel all I/O requests that have been added to the queue, regardless of the thread used to add the device handle.

■ When the thread terminates, the system will automatically cancel all I/O requests sent by the thread. However, if the request is sent to a device handle that has an I/O completion port associated with it, they are not in the canceled column.

■ To cancel the specified I/O request sent to the file handle, we can call cancelioex:

Bool cancelioex (handle hfile, lpoverlapped poverlapped );

Cancelioex is used. We can cancel the pending I/O requests sent by other threads outside the calling thread. this function marks all requests related to the poverlapped parameter in the pending I/O requests of the hfile device as canceled. (in other words, it will cancel the specified I/O request ). if null is passed, all I/O requests related to hfile to be processed will be canceled.

The error code error_operation_aborted is returned for the canceled I/O Request.

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.