Linux fcntl函數設置阻塞與非阻塞

轉自http://www.cnblogs.com/xuyh/p/3273082.htmlhtml

 

用命令F_GETFL和F_SETFL設置文件標誌,好比阻塞與非阻塞緩存

F_SETFL     設置給arg描述符狀態標誌,能夠更改的幾個標誌是:O_APPEND, O_NONBLOCK,O_SYNC和O_ASYNC。性能

命令字(cmd)F_GETFL和F_SETFL的標誌以下面的描述:            spa

O_NONBLOCK       非阻塞I/O;若是read(2)調用沒有可讀取的數據,或者若是write(2)操做將阻塞,read或write調用返回-1和EAGAIN錯誤                            code

O_APPEND             強制每次寫(write)操做都添加在文件大的末尾,至關於open(2)的O_APPEND標誌         htm

 O_DIRECT              最小化或去掉reading和writing的緩存影響.系統將企圖避免緩存你的讀或寫的數據.blog

                                若是不可以避免緩存,那麼它將最小化已經被緩存了的數 據形成的影響.若是這個標誌用的不夠好,將大大的下降性能                     進程

 O_ASYNC              當I/O可用的時候,容許SIGIO信號發送到進程組,例如:當有數據能夠讀的時候cmd

 注意:      在修改文件描述符標誌或文件狀態標誌時必須謹慎,先要取得如今的標誌值,而後按照但願修改它,最後設置新標誌值。不能只是執行F_SETFD或F_SETFL命令,這樣會關閉之前設置的標誌位。string

 

#include <stdio.h> #include <sys/types.h> #include <unistd.h> #include <sys/stat.h> #include <fcntl.h> #include <string.h>

/**********************使能非阻塞I/O******************** *int flags; *if(flags = fcntl(fd, F_GETFL, 0) < 0) *{ * perror("fcntl"); * return -1; *} *flags |= O_NONBLOCK; *if(fcntl(fd, F_SETFL, flags) < 0) *{ * perror("fcntl"); * return -1; *} *******************************************************/

/**********************關閉非阻塞I/O****************** flags &= ~O_NONBLOCK; if(fcntl(fd, F_SETFL, flags) < 0) { perror("fcntl"); return -1; } *******************************************************/

int main() { char buf[10] = {0}; int ret; int flags; //使用非阻塞io
    if(flags = fcntl(STDIN_FILENO, F_GETFL, 0) < 0) { perror("fcntl"); return -1; } flags |= O_NONBLOCK; if(fcntl(STDIN_FILENO, F_SETFL, flags) < 0) { perror("fcntl"); return -1; } while(1) { sleep(2); ret = read(STDIN_FILENO, buf, 9); if(ret == 0) { perror("read--no"); } else { printf("read = %d\n", ret); } write(STDOUT_FILENO, buf, 10); memset(buf, 0, 10); } return 0; }
相關文章
相關標籤/搜索