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


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

 

用命令F_GETFL和F_SETFL設置文件標志,比如阻塞與非阻塞

F_SETFL     設置給arg描述符狀態標志,可以更改的幾個標志是:O_APPEND, O_NONBLOCK,O_SYNC和O_ASYNC。

命令字(cmd)F_GETFL和F_SETFL的標志如下面的描述:            

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

O_APPEND             強制每次寫(write)操作都添加在文件大的末尾,相當於open(2)的O_APPEND標志         

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

                                如果不能夠避免緩存,那么它將最小化已經被緩存了的數 據造成的影響.如果這個標志用的不夠好,將大大的降低性能                     

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

 注意:      在修改文件描述符標志或文件狀態標志時必須謹慎,先要取得現在的標志值,然后按照希望修改它,最后設置新標志值。不能只是執行F_SETFD或F_SETFL命令,這樣會關閉以前設置的標志位。

 

#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; }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM