本文簡要介紹ruby語言中 IO.read_nonblock 的用法。
用法
read_nonblock(maxlen [, options]) → string
read_nonblock(maxlen, outbuf [, options]) → outbuf
在為底層文件說明符設置 O_NONBLOCK 後,使用 read(2) 係統調用從 ios 讀取最多 maxlen 字節。
如果存在可選的 outbuf 參數,則它必須引用 String ,它將接收數據。 outbuf 將僅包含方法調用後接收到的數據,即使它一開始不為空。
read_nonblock 隻是調用 read(2) 係統調用。它會導致 read(2) 係統調用導致的所有錯誤:Errno::EWOULDBLOCK、Errno::EINTR 等。調用者應該注意這些錯誤。
如果異常是 Errno::EWOULDBLOCK 或 Errno::EAGAIN,則通過 IO::WaitReadable 對其進行擴展。所以 IO::WaitReadable 可以用來挽救重試read_nonblock的異常。
read_nonblock 在 EOF 上導致 EOFError 。
在某些平台(例如 Windows)上, IO 對象不支持非阻塞模式,而不是套接字。在這種情況下,將引發 Errno::EBADF。
如果讀取字節緩衝區不為空, read_nonblock 會像 readpartial 一樣從緩衝區讀取。在這種情況下,不調用 read(2) 係統調用。
當 read_nonblock 引發異常類型 IO::WaitReadable 時,不應該調用 read_nonblock 直到 io 可讀以避免繁忙循環。這可以如下進行。
# emulates blocking read (readpartial).
begin
result = io.read_nonblock(maxlen)
rescue IO::WaitReadable
IO.select([io])
retry
end
雖然 IO#read_nonblock 不會引發 IO::WaitWritable 。 OpenSSL::Buffering#read_nonblock 可以提高 IO::WaitWritable 。如果 IO 和 SSL 應該多態使用, IO::WaitWritable 也應該被拯救。示例代碼參見 OpenSSL::Buffering#read_nonblock 的文檔。
請注意,此方法與 readpartial 相同,隻是設置了非阻塞標誌。
通過將關鍵字參數 exception 指定為 false ,您可以指示 read_nonblock 不應引發 IO::WaitReadable 異常,而是返回符號 :wait_readable。在 EOF,它將返回 nil 而不是提高 EOFError 。
相關用法
- Ruby IO.read用法及代碼示例
- Ruby IO.readlines用法及代碼示例
- Ruby IO.readchar用法及代碼示例
- Ruby IO.readpartial用法及代碼示例
- Ruby IO.rewind用法及代碼示例
- Ruby IO.reopen用法及代碼示例
- Ruby IO.raw用法及代碼示例
- Ruby IO.eof用法及代碼示例
- Ruby IO.fileno用法及代碼示例
- Ruby IO.pread用法及代碼示例
- Ruby IO.to_i用法及代碼示例
- Ruby IO.self << object用法及代碼示例
- Ruby IO.tty?用法及代碼示例
- Ruby IO.close_write用法及代碼示例
- Ruby IO.write_nonblock用法及代碼示例
- Ruby IO.set_encoding_by_bom用法及代碼示例
- Ruby IO.syswrite用法及代碼示例
- Ruby IO.close_read用法及代碼示例
- Ruby IO.stat用法及代碼示例
- Ruby IO.pwrite用法及代碼示例
- Ruby IO.ungetc用法及代碼示例
- Ruby IO.noecho用法及代碼示例
- Ruby IO.new用法及代碼示例
- Ruby IO.sysopen用法及代碼示例
- Ruby IO.try_convert用法及代碼示例
注:本文由純淨天空篩選整理自ruby-lang.org大神的英文原創作品 IO.read_nonblock。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。
