CreateFile
功能
Creates or opens a file or I/O device.
函數(shù)原型
HANDLE CreateFile
(
LPCSTR lpFileName,
DWORD dwDesiredAccess,
DWORD dwShareMode,
LPSECURITY_ATTRIBUTES lpSecurityAttributes,
DWORD dwCreationDisposition,
DWORD dwFlagsAndAttributes,
HANDLE hTemplateFile
);
第一個(gè)參數(shù):
lpFileName
The name of the file or device to be created or opened第二個(gè)參數(shù):
dwDesiredAccess
The requested access to the file or device, which can be summarized as read, write, both or neither zero).
值 | 意義 |
---|---|
0 |
If this parameter is zero, the application can query certain metadata(元數(shù)據(jù)) 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:通用
- 第三個(gè)參數(shù):
dwShareMode
The requested sharing mode of the file or device, which can be read, write, both, delete, all of these, or none.
值 | 意義 |
---|---|
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. |
第四個(gè)參數(shù):
lpSecurityAttributes
用于指定安全信息以及句柄的繼承性,一般為NULL
即可第五個(gè)參數(shù):
dwCreationDisposition
An action to take on a file or device that exists or does not exist.
值 | 意義 |
---|---|
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. |
- 第六個(gè)參數(shù):
dwFlagsAndAttributes
值 | 意義 |
---|---|
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(同時(shí)) 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. |
備注 | 以上表格只包含了部分值锥腻,還有很多值沒(méi)有包含 |
- 第七個(gè)參數(shù):
hTemplateFile
一般為NULL
返回值
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
參考資料
- https://docs.microsoft.com/en-us/windows/desktop/api/FileAPI/nf-fileapi-createfilea
- 與設(shè)備相關(guān)的細(xì)節(jié)球拦,務(wù)必參考上述網(wǎng)址
使用文件設(shè)備
函數(shù) | 功能 |
---|---|
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基礎(chǔ)
- 一個(gè)線程向設(shè)備發(fā)出一個(gè)異步I/O請(qǐng)求,這個(gè)I/O 請(qǐng)求被傳給設(shè)備驅(qū)動(dòng)程序王暗,后者負(fù)責(zé)完成實(shí)際的I/O操作。當(dāng)驅(qū)動(dòng)程序在等待設(shè)備響應(yīng)時(shí)序攘,應(yīng)用程序的線程并不會(huì)因?yàn)橐鹊絀/O請(qǐng)求完成而被掛起
- 在執(zhí)行異步設(shè)備I/O的時(shí)候渠脉,必須傳入一個(gè)已經(jīng)初始化的OVERLAPPED結(jié)構(gòu)
typedef struct _OVERLAPPED {
ULONG_PTR Internal;
ULONG_PTR InternalHigh;
union {
struct {
DWORD Offset;
DWORD OffsetHigh;
} DUMMYSTRUCTNAME;
PVOID Pointer;
} DUMMYUNIONNAME;
HANDLE hEvent;
} OVERLAPPED, *LPOVERLAPPED;
參數(shù) | 意義 |
---|---|
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(機(jī)制)), 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(同時(shí)) 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. |
注意點(diǎn)
- 設(shè)備驅(qū)動(dòng)程序不會(huì)以先入先出的方式來(lái)處理隊(duì)列中的I/O請(qǐng)求
- 如果請(qǐng)求的I/O操作是以同步方式進(jìn)行的,那么
ReadFile
WriteFile
返回非零值- 如果請(qǐng)求的I/O操作是以異步方式進(jìn)行的档叔,那么調(diào)用上述兩個(gè)函數(shù)返回
FALSE
桌粉,此時(shí)必須調(diào)用GetLastError
來(lái)檢查,若返回ERROR_IO_PENDING
衙四,那么I/O請(qǐng)求已經(jīng)被成功添加到隊(duì)列中铃肯,否則表示I/O請(qǐng)求無(wú)法被添加到設(shè)備驅(qū)動(dòng)程序的隊(duì)列中- 在異步I/O請(qǐng)求完成前,一定不能移動(dòng)或者銷(xiāo)毀發(fā)出I/O請(qǐng)求時(shí)所使用的OVERLAPPED結(jié)構(gòu)
取消隊(duì)列中的異步I/O請(qǐng)求
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.- 關(guān)閉設(shè)備句柄传蹈,來(lái)取消已經(jīng)添加到隊(duì)列中的所有I/O請(qǐng)求押逼,而不管他們是哪個(gè)線程添加的
- 當(dāng)線程終止時(shí),系統(tǒng)會(huì)自動(dòng)取消該線程發(fā)出的所有I/O請(qǐng)求惦界,除非發(fā)出I/O請(qǐng)求的設(shè)備具有與之關(guān)聯(lián)的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. 備注:此函數(shù)可以針對(duì)設(shè)備指定的某次I/O請(qǐng)求也可以針對(duì)設(shè)備的全部I/O請(qǐng)求
接收異步I/O請(qǐng)求完成通知
觸發(fā)設(shè)備內(nèi)核對(duì)象
-
ReadFile
WriteFile
函數(shù)在將I/O請(qǐng)求添加到隊(duì)列前挑格,會(huì)先將設(shè)備內(nèi)核對(duì)象設(shè)為非觸發(fā)狀態(tài),當(dāng)設(shè)備驅(qū)動(dòng)完成請(qǐng)求后沾歪,驅(qū)動(dòng)程序會(huì)將設(shè)備內(nèi)核對(duì)象置為觸發(fā)狀態(tài)
觸發(fā)事件內(nèi)核對(duì)象
- 利用
OVERLAPPED
的hEvent
來(lái)等待特定I/O請(qǐng)求的完成
可提醒I/O
- 當(dāng)系統(tǒng)創(chuàng)建一個(gè)線程的時(shí)候漂彤,會(huì)同時(shí)創(chuàng)建一個(gè)與線程相關(guān)聯(lián)的隊(duì)列,稱(chēng)為異步過(guò)程調(diào)用隊(duì)列(APC)。
- 當(dāng)發(fā)出一個(gè)I/O請(qǐng)求的時(shí)候挫望,我們可以告訴設(shè)備驅(qū)動(dòng)程序在調(diào)用線程的APC隊(duì)列中添加一項(xiàng)立润,需使用
ReadFileEx
WriteFileEx
- 當(dāng)線程處于可提醒狀態(tài)時(shí),系統(tǒng)會(huì)檢查他的APC隊(duì)列媳板,對(duì)隊(duì)列中的每一項(xiàng)桑腮,系統(tǒng)會(huì)調(diào)用其回調(diào)函數(shù)(此調(diào)用過(guò)程是同一個(gè)線程進(jìn)行的,不存在線程同步的問(wèn)題)蛉幸,并傳入I/O錯(cuò)誤碼破讨、已傳輸字節(jié)數(shù)、
OVERLAPPED
結(jié)構(gòu)的地址 - 將線程置于可提醒狀態(tài)的常用函數(shù):
SleepEx
巨缘、WaitForSingleObjectEx
添忘、WaitForMultipleObjectsEx
、GetQueuedCompletionStatusEx
若锁。在調(diào)用上述函數(shù)時(shí)搁骑,如果線程的APC隊(duì)列不為空,則系統(tǒng)不會(huì)讓線程進(jìn)入睡眠狀態(tài)又固。若線程至少處理了APC隊(duì)列中的一項(xiàng)仲器,上述函數(shù)會(huì)返回WAIT_IO_COMPLETION
可提醒I/O的劣勢(shì)
- 必須使用回調(diào)函數(shù),導(dǎo)致代碼變的復(fù)雜
- 發(fā)出I/O請(qǐng)求的線程必須同時(shí)對(duì)完成通知進(jìn)行處理仰冠,不存在負(fù)載均衡機(jī)制
-
QueueUserApc
:Adds a user-mode asynchronous procedure call (APC) object to the APC queue of the specified thread.(是一種高效的線程通信手段乏冀,甚至可以跨越進(jìn)程界限)
I/O完成端口
傳統(tǒng)的并發(fā)模型缺點(diǎn)
- 需要?jiǎng)?chuàng)建大量的線程,造成額外的開(kāi)銷(xiāo)
- 大量的線程并發(fā)執(zhí)行洋只,會(huì)造成嚴(yán)重的上下文切換問(wèn)題辆沦,導(dǎo)致降低了性能
CreateIoCompletionPort
HANDLE WINAPI CreateIoCompletionPort
(
HANDLE FileHandle,
HANDLE ExistingCompletionPort,
ULONG_PTR CompletionKey,
DWORD NumberOfConcurrentThreads
);
功能
Creates an input/output (I/O) completion port and associates it with a specified file handle, or creates an I/O completion port that is not yet associated with a file handle, allowing association at a later time.
Associating an instance of an opened file handle with an I/O completion port allows a process to receive notification of the completion of asynchronous I/O operations involving that file handle.FileHandle
An open file handle or INVALID_HANDLE_VALUE.
The handle must be to an object that supports overlapped I/O.
If a handle is provided, it has to have been opened for overlapped I/O completion(實(shí)現(xiàn)). For example, you must specify the FILE_FLAG_OVERLAPPED flag when using the CreateFile function to obtain the handle.
If INVALID_HANDLE_VALUE is specified, the function creates an I/O completion port without associating it with a file handle. In this case, theExistingCompletionPort
parameter must be NULL and theCompletionKey
parameter is ignored.ExistingCompletionPort
A handle to an existing I/O completion port or NULL.
If this parameter specifies an existing I/O completion port, the function associates it with the handle specified by the FileHandle parameter. The function returns the handle of the existing I/O completion port if successful; it does not create a new I/O completion port.
If this parameter is NULL, the function creates a new I/O completion port and, if the FileHandle parameter is valid, associates it with the new I/O completion port. Otherwise no file handle association occurs. The function returns the handle to the new I/O completion port if successful.CompletionKey
The per-handle user-defined completion key that is included in every I/O completion packet(信息包) for the specified file handle.NumberOfConcurrentThreads
The maximum number of threads that the operating(操作) system can allow to concurrently(同時(shí)) process I/O completion packets for the I/O completion port. This parameter is ignored if the ExistingCompletionPort parameter is not NULL.
If this parameter is zero, the system allows as many concurrently running threads as there are processors(中央處理器) in the system.返回值:失敗返回NULL。成功分為2種情況识虚,在上面已經(jīng)闡述
GetQueuedCompletionStatus
BOOL WINAPI GetQueuedCompletionStatus
(
HANDLE CompletionPort,
LPDWORD lpNumberOfBytesTransferred,
PULONG_PTR lpCompletionKey,
LPOVERLAPPED * lpOverlapped,
DWORD dwMilliseconds
);
功能
Attempts to dequeue(出列) an I/O completion packet from the specified I/O completion port. If there is no completion packet queued, the function waits for a pending I/O operation associated with the completion port to complete.CompletionPort
A handle to the completion port.lpNumberOfBytesTransferred
A pointer to a variable that receives the number of bytes transferred during an I/O operation that has completed.lpCompletionKey
A pointer to a variable that receives the completion key value associated with the file handle whose I/O operation has completed. A completion key is a per-file key that is specified in a call to CreateIoCompletionPort.lpOverlapped
A pointer to a variable that receives the address of the OVERLAPPED structure that was specified(指定) when the completed I/O operation was started.
Even if you have passed the function a file handle associated with a completion port and a valid OVERLAPPED structure, an application can prevent completion port notification. This is done by specifying a valid event handle for the hEvent member of the OVERLAPPED structure, and setting its low-order bit. A valid event handle whose low-order bit is set keeps I/O completion from being queued to the completion port.(這段話(huà)的意思大致是:即使設(shè)備已經(jīng)關(guān)聯(lián)了一個(gè)I/O完成端口肢扯,也可以不將該設(shè)備的I/O請(qǐng)求添加到I/O完成端口的隊(duì)列中,方式是為OVERLAPPED結(jié)構(gòu)分配一個(gè)有效的事件內(nèi)核對(duì)象并與1進(jìn)行或操作)dwMilliseconds
The number of milliseconds that the caller is willing to wait for a completion packet to appear at the completion port. If a completion packet does not appear within the specified time, the function times out, returns FALSE, and sets *lpOverlapped to NULL.
If dwMilliseconds is INFINITE, the function will never time out. If dwMilliseconds is zero and there is no I/O operation to dequeue, the function will time out immediately.返回值
Returns nonzero (TRUE) if successful or zero (FALSE) otherwise.備注
This function associates a thread with the specified completion port. A thread can be associated with at most one completion port.
PostQueuedCompletionStatus
BOOL WINAPI PostQueuedCompletionStatus
(
HANDLE CompletionPort, //被投向模擬請(qǐng)求的I/O完成端口
DWORD dwNumberOfBytesTransferred, //以傳遞字節(jié)數(shù)
ULONG_PTR dwCompletionKey, //完成建值
LPOVERLAPPED lpOverlapped //被投遞的OVERLAPPED結(jié)構(gòu)地址
);
- 功能
Posts an I/O completion packet to an I/O completion port.
I/O完成端口備注
- I/O完成端口對(duì)應(yīng)線程池的線程個(gè)數(shù)一般是取主機(jī)的CPU數(shù)量乘以2
- 利用I/O完成端口寫(xiě)的一個(gè)TCP通信的例子:http://www.reibang.com/p/09388ecaf47b