One of the actual deviceiocontrol: access the device driver through APIS

Source: Internet
Author: User
Tags types of functions

QIn NT/2000/XP, I want to write applications using VCProgramAccess hardware devices, such as obtaining disk parameters, reading and writing absolute sector data, and testing the actual speed of the optical drive. Where should I start?

AIn NT/2000/XP, applications can use the API function deviceiocontrol to access devices, obtain information, send commands, and exchange data. Use this interface function to send the correct control code and data to the specified device driver, and then analyze its response to achieve our goal.

The function prototype of deviceiocontrol is

Bool deviceiocontrol (handle hdevice,// Device handleDWORD dwiocontrolcode,// Control codeLpvoid lpinbuffer,// Input data buffer pointerDWORD ninbuffersize,// Input data buffer LengthLpvoid lpoutbuffer,// Output data buffer pointerDWORD noutbuffersize,// Output data buffer LengthLpdword lpbytesreturned,// Actual length of the output data unitLpoverlapped// Overlapping operation structure pointer);

The device handle is used to identify the device you are accessing.

Send different control codes to call different types of functions of the device driver. In the header file winioctl. H, the predefined standard device control codes start with IOCTL or fsctl. For example, ioctl_disk_get_drive_geometry is the control code for the structure parameters (media type, number of cylinders, number of tracks per cylinder, number of sectors per track, etc.) of the physical drive, fsctl_lock_volume is the control code for locking the volume of the logical drive.

Whether the input/output data buffer is required, the structure of the buffer, and the size of the byte space are determined by the different operation types of different devices. In the header file winioctl. H, some input/output data structures have been predefined for the standard device. If the pointer of the overlapping operation structure is set to null, deviceiocontrol will block the call. Otherwise, the asynchronous operation should be performed during programming.

QWhere is the device handle obtained?

AYou can use the createfile API to obtain the device handle. Its prototype is

Handle createfile (lpctstr lpfilename,// File name/device pathDWORD dwdesiredaccess,// Access methodDWORD dw1_mode,// Share modeLpsecurity_attributes lpsecurityattributes,// Security descriptor pointerDWORD dwcreationdisposition,// Creation MethodDWORD dwflagsandattributes,// File attributes and symbolsHandle htemplatefile// Template file handle);

The createfile function is very useful. Here we use it to "open" the device driver to get the device handle. After the operation is complete, use closehandle to close the device handle.

Different from common file names, the device driver's "file name" (often referred to as "device path") format is fixed as "//. /devicename "(note that in the C program, this string is written as" //. // devicename "), devicename must be the same as the device name defined in the device driver.

Generally, when createfile is called to obtain the device handle, the access mode parameter is set to 0 or generic_read | generic_write, the sharing mode parameter is set to file_1__read | file_1__write, And the creation mode parameter is set to open_existing, other parameters are set to 0 or null.

QBut how do I know what the device name is?

AThe names of some storage devices are defined by Microsoft and cannot be changed. The general list is as follows:

Floppy disk drive A:, B:
Hard Disk logical Partition C:, D:, E :,...
Physical drive Physicaldrivex
CD-ROM, DVD/ROM Cdromx
Tape drive Tapex

The physical drive does not include the soft drive and optical drive. Logical drives can be hard disk partitions (volumes), optical drives, Mo, and CF cards of the IDE, SCSI, PCMCIA, and USB interfaces, or even Virtual Disks. X = 0, 1, 2 ......

Other device names must be obtained by calling the device management function family using the guid of the driver interface.

QA simple example shows how to access the device driver through deviceiocontrol.

AHere is a demo program Excerpted from msdn to demonstrate how to obtain basic hard disk parameters through deviceiocontrol in NT/2000/XP.

 /* The Code of interest is in the subroutine getdrivegeometry. The code in main shows how to interpret the results of The IOCTL call .*/    # Include   <Windows. h>  # Include   <Winioctl. h> Bool getdrivegeometry (disk_geometry * PDG) {handle hdevice; // Handle to the drive to be examined Bool bresult; // Results flag DWORD junk; // Discard results Hdevice = createfile ( "////. // Physicaldrive0" , // Drive to open                      0 , // No access to the drive File_pai_read | // Share mode File_pai_write, null, // Default security attributes Open_existing, // Disposition                      0 , // File attributes Null );// Do not copy file attributes        If (Hdevice = invalid_handle_value) // Cannot open the drive { Return (False);} bresult = deviceiocontrol (hdevice, // Device to be queried Ioctl_disk_get_drive_geometry, // Operation to perform Null, 0 , // No input buffer PDG, Sizeof (* PDG ), // Output buffer & Junk,// # Bytes returned (Lpoverlapped) null ); // Synchronous I/O Closehandle (hdevice ); Return (Bresult );} Int Main ( Int Argc, Char * Argv []) {disk_geometry PDG; // Disk drive geometry structure Bool bresult; // Generic results flag Ulonglong disksize; // Size of the drive, in bytes Bresult = getdrivegeometry (& PDG ); If (Bresult) {printf ("Cylinders = % i64d/N" , PDG. cylinders); printf ( "Tracks per cylinder = % LD/N" , (Ulong) PDG. trackspercylinder); printf ( "Sectors per track = % LD/N" , (Ulong) PDG. sectorspertrack); printf ( "Bytes per sector = % LD/N" , (Ulong) PDG. bytespersector); disksize = PDG. Cylinders. quadpart * (ulong) PDG. trackspercylinder * (ulong) PDG. sectorspertrack * (ulong) PDG. bytespersector; printf ( "Disk size = % i64d (bytes) = % i64d (MB)/n" , Disksize, disksize /( 1024 * 1024 ));} Else {Printf ("Getdrivegeometry failed. Error % lD./N" , Getlasterror ());} Return (( Int ) Bresult );}

QIf you change the device name to "A:", you can take the disk parameter, and change it to "cdrom0", you can take the CDROM parameter, right?

AI will not answer this question for the moment. Please try it.

Now let's summarize the three steps to access the device driver through deviceiocontrol: first, use createfile to get the device handle, and then use deviceiocontrol to perform I/O with the device, do not forget to use closehandle to close the device handle.

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.