Windows I/O

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

參考資料
使用文件設(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ì)象
  • 利用OVERLAPPEDhEvent來(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添忘、WaitForMultipleObjectsExGetQueuedCompletionStatusEx若锁。在調(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, the ExistingCompletionPort parameter must be NULL and the CompletionKey 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
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末担锤,一起剝皮案震驚了整個(gè)濱河市蔚晨,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌肛循,老刑警劉巖铭腕,帶你破解...
    沈念sama閱讀 218,284評(píng)論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異多糠,居然都是意外死亡累舷,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,115評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門(mén)熬丧,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)笋粟,“玉大人怀挠,你說(shuō)我怎么就攤上這事析蝴『Σ叮” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 164,614評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵闷畸,是天一觀的道長(zhǎng)尝盼。 經(jīng)常有香客問(wèn)我,道長(zhǎng)佑菩,這世上最難降的妖魔是什么盾沫? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,671評(píng)論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮殿漠,結(jié)果婚禮上赴精,老公的妹妹穿的比我還像新娘。我一直安慰自己绞幌,他們只是感情好蕾哟,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,699評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著莲蜘,像睡著了一般谭确。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上票渠,一...
    開(kāi)封第一講書(shū)人閱讀 51,562評(píng)論 1 305
  • 那天逐哈,我揣著相機(jī)與錄音问顷,去河邊找鬼肠骆。 笑死荷科,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播厚柳,決...
    沈念sama閱讀 40,309評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼烧董,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼龙填!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起窘拯,我...
    開(kāi)封第一講書(shū)人閱讀 39,223評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤壁酬,失蹤者是張志新(化名)和其女友劉穎希俩,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體鳞上,經(jīng)...
    沈念sama閱讀 45,668評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡这吻,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,859評(píng)論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了因块。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片橘原。...
    茶點(diǎn)故事閱讀 39,981評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡籍铁,死狀恐怖涡上,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情拒名,我是刑警寧澤吩愧,帶...
    沈念sama閱讀 35,705評(píng)論 5 347
  • 正文 年R本政府宣布,位于F島的核電站增显,受9級(jí)特大地震影響雁佳,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜同云,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,310評(píng)論 3 330
  • 文/蒙蒙 一糖权、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧炸站,春花似錦星澳、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,904評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至阀坏,卻和暖如春如暖,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背忌堂。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,023評(píng)論 1 270
  • 我被黑心中介騙來(lái)泰國(guó)打工盒至, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人士修。 一個(gè)月前我還...
    沈念sama閱讀 48,146評(píng)論 3 370
  • 正文 我出身青樓枷遂,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親李命。 傳聞我的和親對(duì)象是個(gè)殘疾皇子登淘,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,933評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容