亚洲av成人无遮挡网站在线观看,少妇性bbb搡bbb爽爽爽,亚洲av日韩精品久久久久久,兔费看少妇性l交大片免费,无码少妇一区二区三区
Chinaunix
標題:
非阻塞IO
[打印本頁]
作者:
linuxer_lhw
時間:
2009-11-04 20:04
標題:
非阻塞IO
非阻塞I/O使我們可以調用不會永遠阻塞的I/O操作,例如read和write。如果 這種操作不能完成,則立即出錯返回,表示該操作如繼續(xù)執(zhí)行將繼續(xù)阻塞下去。
對于一個給定的描述符有兩種方法對其指定非阻塞I/O:
1. 如果是調用open以獲得該描述符,則可指定O_NONBLOCK標志。
2. 對于已經(jīng)打開的一個描述符,則可調用fcntl,對其打開O_NONBOCK文件狀態(tài)標 志
可見阻塞還是非阻塞與read、write等系統(tǒng)調用和文件(如普通的磁盤文件或socket)無關,而是與是否用上面那兩個方法設置文件描述符的屬性O_NONBLOCK有關.默認情況下,文件的IO是阻塞IO,除非用上面兩個方法設置非阻塞標志。
下面的程序是一個非阻塞I/O的實例,它從標準輸入讀100,000字節(jié),并試圖將它們 寫到標準輸出上。該程序先將標準輸出設置為非阻塞的,然后用for循環(huán)進行輸出 ,每次寫的結果都在標準出錯上打印。
#include sys/types.h>
#include errno.h>
#include fcntl.h>
#include "ourhdr.h"
char buf[100000];
int
main(void)
{
int ntowrite, nwrite;
char *ptr;
ntowrite = read(STDIN_FILENO, buf, sizeof(buf));
fprintf(stderr, "read %d bytes\n", ntowrite);
set_fl(STDOUT_FILENO, O_NONBLOCK); /* set nonblocking */
for (ptr = buf; ntowrite > 0; ) {
errno = 0;
nwrite = write(STDOUT_FILENO, ptr, ntowrite);
fprintf(stderr, "nwrite = %d, errno = %d\n", nwrite, errno);
if (nwrite > 0) {
ptr += nwrite;
ntowrite -= nwrite;
}
}
clr_fl(STDOUT_FILENO, O_NONBLOCK); /* clear nonblocking */
exit(0);
}
標準輸出是普通文件,則可以期望write只執(zhí)行一次。
$a.out temp.file 先試一普 文件
read 100000 bytes
nwrite-100000, errno=0 一次寫
$ls -l temp.file 驗輸出文件長度
-rw-rw-r-1 stevens 100000 Nev 21 16:27 temp.file
但是,若標準輸出是終端,則可期望write有時會返回一個數(shù)字,有時則出錯返回
$ a.out stderr.out 向終端輸出 大量輸出至終端
$ cat stderr.out
read 100000 bytes
nwrite=8192, errno=0
nwrite=8192, errno=0
nwrite=-1, errno=11
…
nwrite=4096,errno=0
nwrite=-1, errno=11
…
nwrite=4096,errno=0
nwrite=-1, errno=11
…
nwrite=4096,errno=0
nwrite=-1, errno=11
…
nwrite=-1, errno=11
…
nwrite=4096,errno=0 …等等
在該系統(tǒng)上,errno11是EAGAIN((或者EWOULDBLOCK,這兩個宏定義的值相同))。此系統(tǒng)上的終端驅動程序總是一次接收4096或8192字節(jié)。在另一個系統(tǒng)上,前三個write返回2005,1822和1811,然后是96次出錯 返回,接著是返回1864等等。 每個write能寫多少字節(jié)是依賴于系統(tǒng)的。 在此實例中,程序發(fā)出了數(shù)千個write調用,但是只有20個左右是真正輸出數(shù)據(jù)的 ,其余的則出錯返回。這種形式的循環(huán)稱為輪詢,在多用戶系統(tǒng)上它浪費了CPU時 間。 ,調用者應該試著再讀一次(again),這樣可以同時監(jiān)視多個設備。
#include "apue.h"
#include fcntl.h>
void
set_fl(int fd, int flags) /* flags are file status flags to turn on */
{
int val;
if ((val = fcntl(fd, F_GETFL, 0)) 0)
err_sys("fcntl F_GETFL error");
val |= flags; /* turn on flags */
if (fcntl(fd, F_SETFL, val) 0)
err_sys("fcntl F_SETFL error");
}
void
cli_fl(int fd, int flags) /* flags are file status flags to turn off*/
{
int val;
if ((val = fcntl(fd, F_GETFL, 0)) 0)
err_sys("fcntl F_GETFL error");
val &= ~flags; /* turn off flags */
if (fcntl(fd, F_SETFL, val) 0)
err_sys("fcntl F_SETFL error");
}
本文來自ChinaUnix博客,如果查看原文請點:
http://blog.chinaunix.net/u3/103462/showart_2086453.html
歡迎光臨 Chinaunix (http://72891.cn/)
Powered by Discuz! X3.2