- 論壇徽章:
- 0
|
非阻塞I/O使我們可以調(diào)用不會永遠(yuǎn)阻塞的I/O操作,例如read和write。如果 這種操作不能完成,則立即出錯返回,表示該操作如繼續(xù)執(zhí)行將繼續(xù)阻塞下去。
對于一個給定的描述符有兩種方法對其指定非阻塞I/O:
1. 如果是調(diào)用open以獲得該描述符,則可指定O_NONBLOCK標(biāo)志。
2. 對于已經(jīng)打開的一個描述符,則可調(diào)用fcntl,對其打開O_NONBOCK文件狀態(tài)標(biāo) 志
可見阻塞還是非阻塞與read、write等系統(tǒng)調(diào)用和文件(如普通的磁盤文件或socket)無關(guān),而是與是否用上面那兩個方法設(shè)置文件描述符的屬性O(shè)_NONBLOCK有關(guān).默認(rèn)情況下,文件的IO是阻塞IO,除非用上面兩個方法設(shè)置非阻塞標(biāo)志。
下面的程序是一個非阻塞I/O的實例,它從標(biāo)準(zhǔn)輸入讀100,000字節(jié),并試圖將它們 寫到標(biāo)準(zhǔn)輸出上。該程序先將標(biāo)準(zhǔn)輸出設(shè)置為非阻塞的,然后用for循環(huán)進(jìn)行輸出 ,每次寫的結(jié)果都在標(biāo)準(zhǔ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);
}
標(biāo)準(zhǔn)輸出是普通文件,則可以期望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
但是,若標(biāo)準(zhǔn)輸出是終端,則可期望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)上的終端驅(qū)動程序總是一次接收4096或8192字節(jié)。在另一個系統(tǒng)上,前三個write返回2005,1822和1811,然后是96次出錯 返回,接著是返回1864等等。 每個write能寫多少字節(jié)是依賴于系統(tǒng)的。 在此實例中,程序發(fā)出了數(shù)千個write調(diào)用,但是只有20個左右是真正輸出數(shù)據(jù)的 ,其余的則出錯返回。這種形式的循環(huán)稱為輪詢,在多用戶系統(tǒng)上它浪費了CPU時 間。 ,調(diào)用者應(yīng)該試著再讀一次(again),這樣可以同時監(jiān)視多個設(shè)備。
#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 |
|