Windows I/O

2018-08-13  本文已影响0人  szn好色仙人
CreateFile
功能

Creates or opens a file or I/O device.

函数原型
HANDLE CreateFile
(
    LPCSTR                lpFileName,
    DWORD                 dwDesiredAccess,
    DWORD                 dwShareMode,
    LPSECURITY_ATTRIBUTES lpSecurityAttributes,
    DWORD                 dwCreationDisposition,
    DWORD                 dwFlagsAndAttributes,
    HANDLE                hTemplateFile
);
意义
0 If this parameter is zero, the application can query certain metadata(元数据) such as file, directory, or device attributes without accessing that file or device, even if GENERIC_READ access would have been denied.
GENERIC_READ Read access
GENERIC_WRITE Write access
GENERIC_EXECUTE Execute access
GENERIC_ALL All possible access rights

generic:通用

意义
0 Prevents other processes from opening a file or device if they request delete, read, or write access.
FILE_SHARE_READ Enables subsequent(随后) open operations on a file or device to request read access.
Otherwise, other processes cannot open the file or device if they request read access.
If this flag is not specified, but the file or device has been opened for read access, the function fails.
FILE_SHARE_WRITE Enables subsequent open operations on a file or device to request write access.
Otherwise, other processes cannot open the file or device if they request write access.
If this flag is not specified, but the file or device has been opened for write access or has a file mapping with write access, the function fails.
FILE_SHARE_DELETE Enables subsequent open operations on a file or device to request delete access.
Otherwise, other processes cannot open the file or device if they request delete access.
If this flag is not specified, but the file or device has been opened for delete access, the function fails.
Note Delete access allows both delete and rename operations.
意义
CREATE_ALWAYS Creates a new file, always.
If the specified file exists and is writable, the function overwrites the file, the function succeeds, and last-error code is set to ERROR_ALREADY_EXISTS (183).
If the specified file does not exist and is a valid path, a new file is created, the function succeeds, and the last-error code is set to zero.
CREATE_NEW Creates a new file, only if it does not already exist.
If the specified file exists, the function fails and the last-error code is set to ERROR_FILE_EXISTS (80).
If the specified file does not exist and is a valid path to a writable location, a new file is created.
OPEN_ALWAYS Opens a file, always.
If the specified file exists, the function succeeds and the last-error code is set to ERROR_ALREADY_EXISTS (183).
If the specified file does not exist and is a valid path to a writable location, the function creates a file and the last-error code is set to zero.
OPEN_EXISTING Opens a file or device, only if it exists.
If the specified file or device does not exist, the function fails and the last-error code is set to ERROR_FILE_NOT_FOUND (2).
TRUNCATE_EXISTING Opens a file and truncates it so that its size is zero bytes, only if it exists.
If the specified file does not exist, the function fails and the last-error code is set to ERROR_FILE_NOT_FOUND (2).
The calling process must open the file with the GENERIC_WRITE bit set as part of the dwDesiredAccess parameter.
意义
FILE_ATTRIBUTE_NORMAL The file does not have other attributes set. This attribute is valid only if used alone.
FILE_ATTRIBUTE_NORMAL being the most common default value for files.
FILE_FLAG_DELETE_ON_CLOSE The file is to be deleted immediately after all of its handles are closed, which includes the specified handle and any other open or duplicated handles.
If there are existing open handles to a file, the call fails unless they were all opened with the FILE_SHARE_DELETE share mode.
Subsequent open requests for the file fail, unless the FILE_SHARE_DELETE share mode is specified.
FILE_FLAG_OVERLAPPED The file or device is being opened or created for asynchronous(异步) I/O.
When subsequent I/O operations are completed on this handle, the event specified in the OVERLAPPED structure will be set to the signaled state.
If this flag is specified, the file can be used for simultaneous(同时) read and write operations.
If this flag is not specified, then I/O operations are serialized, even if the calls to the read and write functions specify an OVERLAPPED structure.
备注 以上表格只包含了部分值,还有很多值没有包含
返回值

If the function succeeds, the return value is an open handle to the specified file, device, named pipe, or mail slot.
If the function fails, the return value is INVALID_HANDLE_VALUE

参考资料
使用文件设备
函数 功能
GetFileSizeEx Retrieves the size of the specified file.
SetFilePointerEx Moves the file pointer of the specified file.
SetEndOfFile Sets the physical file size for the specified file to the current position of the file pointer.
The physical file size is also referred to as the end of the file. The SetEndOfFile function can be used to truncate or extend a file.
ReadFile Reads data from the specified file or input/output (I/O) device. Reads occur at the position specified by the file pointer if supported by the device.
This function is designed for both synchronous and asynchronous operations. For a similar function designed solely(仅仅) for asynchronous operation, see ReadFileEx.
WriteFile Writes data to the specified file or input/output (I/O) device.
This function is designed for both synchronous and asynchronous operation. For a similar function designed solely for asynchronous operation, see WriteFileEx.
FlushFileBuffers Flushes the buffers of a specified file and causes all buffered data to be written to a file.
CancelSynchronousIo Marks pending synchronous I/O operations that are issued by the specified thread as canceled.
异步I/O基础
typedef struct _OVERLAPPED {
    ULONG_PTR Internal;
    ULONG_PTR InternalHigh;
    union {
        struct {
            DWORD Offset;
            DWORD OffsetHigh;
        } DUMMYSTRUCTNAME;
        PVOID Pointer;
    } DUMMYUNIONNAME;

    HANDLE  hEvent;
} OVERLAPPED, *LPOVERLAPPED;
参数 意义
Internal The status code for the I/O request. When the request is issued, the system sets this member to STATUS_PENDING to indicate that the operation has not yet started. When the request is completed, the system sets this member to the status code for the completed request.
The Internal member was originally reserved for system use and its behavior may change.
InternalHigh The number of bytes transferred for the I/O request. The system sets this member if the request is completed without errors.
The InternalHigh member was originally(起初) reserved for system use and its behavior may change.
offset The low-order portion(一部分) of the file position at which to start the I/O request, as specified by the user.
This member is nonzero only when performing I/O requests on a seeking device that supports the concept(概念) of an offset (also referred to as a file pointer mechanism(机制)), such as a file. Otherwise, this member must be zero.
OffsetHigh The high-order portion of the file position at which to start the I/O request, as specified by the user.
This member is nonzero only when performing I/O requests on a seeking device that supports the concept of an offset (also referred to as a file pointer mechanism), such as a file. Otherwise, this member must be zero.
Pointer Reserved for system use; do not use after initialization to zero.
hEvent A handle to the event that will be set to a signaled state by the system when the operation has completed.
The user must initialize this member either to zero or a valid event handle using the CreateEvent function before passing this structure to any overlapped functions.
This event can then be used to synchronize(同步) simultaneous(同时) I/O requests for a device.
Functions such as ReadFile and WriteFile set this handle to the nonsignaled state before they begin an I/O operation. When the operation has completed, the handle is set to the signaled state.
注意点
  • 设备驱动程序不会以先入先出的方式来处理队列中的I/O请求
  • 如果请求的I/O操作是以同步方式进行的,那么ReadFile WriteFile返回非零值
  • 如果请求的I/O操作是以异步方式进行的,那么调用上述两个函数返回FALSE,此时必须调用GetLastError来检查,若返回ERROR_IO_PENDING,那么I/O请求已经被成功添加到队列中,否则表示I/O请求无法被添加到设备驱动程序的队列中
  • 在异步I/O请求完成前,一定不能移动或者销毁发出I/O请求时所使用的OVERLAPPED结构
取消队列中的异步I/O请求
  • CancelIo Cancels all pending input and output (I/O) operations that are issued by the calling thread for the specified file. The function does not cancel I/O operations that other threads issue for a file handle.
  • 关闭设备句柄,来取消已经添加到队列中的所有I/O请求,而不管他们是哪个线程添加的
  • 当线程终止时,系统会自动取消该线程发出的所有I/O请求,除非发出I/O请求的设备具有与之关联的I/O完成端口
  • CancelIoEx Marks any outstanding I/O operations for the specified file handle. The function only cancels I/O operations in the current process, regardless(不顾后果) of which thread created the I/O operation. 备注:此函数可以针对设备指定的某次I/O请求也可以针对设备的全部I/O请求
接收异步I/O请求完成通知
触发设备内核对象
触发事件内核对象
可提醒I/O
可提醒I/O的劣势
  • 必须使用回调函数,导致代码变的复杂
  • 发出I/O请求的线程必须同时对完成通知进行处理,不存在负载均衡机制
I/O完成端口
传统的并发模型缺点
  • 需要创建大量的线程,造成额外的开销
  • 大量的线程并发执行,会造成严重的上下文切换问题,导致降低了性能
CreateIoCompletionPort
HANDLE WINAPI CreateIoCompletionPort
(
    HANDLE FileHandle,
    HANDLE ExistingCompletionPort,
    ULONG_PTR CompletionKey,
    DWORD NumberOfConcurrentThreads
);
GetQueuedCompletionStatus
BOOL WINAPI GetQueuedCompletionStatus
(
    HANDLE CompletionPort,
    LPDWORD lpNumberOfBytesTransferred,
    PULONG_PTR lpCompletionKey,
    LPOVERLAPPED * lpOverlapped,
    DWORD dwMilliseconds
);
PostQueuedCompletionStatus
BOOL WINAPI PostQueuedCompletionStatus
(
    HANDLE CompletionPort,              //被投向模拟请求的I/O完成端口
    DWORD dwNumberOfBytesTransferred,   //以传递字节数
    ULONG_PTR dwCompletionKey,          //完成建值
    LPOVERLAPPED lpOverlapped           //被投递的OVERLAPPED结构地址
);
I/O完成端口备注
上一篇 下一篇

猜你喜欢

热点阅读