#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #define ERR_EXIT( m ) \ do \ { \ perror( m ); \ exit( EXIT_FAILURE ); \ }while( 0 ) //設置某個文件狀態 void set_flag( int fd, int flags ); //清除某個文件狀態 void clear_flag( int fd, int flags ); int main( int argc, char* argv[] ) { char buf[64] = { 0 }; int nread; //設置非阻塞狀態 set_flag( 0, O_NONBLOCK ); //清除非阻塞狀態, 讀取標準輸入又變成阻塞 clear_flag( 0, O_NONBLOCK ); nread = read( 0, buf, 64 ); if( -1 == nread ) { ERR_EXIT( "獲取輸入失敗" ); } printf( "buf=%s\n", buf ); return 0; } void set_flag( int fd, int flags ) { int oldflag; oldflag = fcntl( fd, F_GETFL, 0 ); if( -1 == oldflag ) { ERR_EXIT( "獲取原來的狀態失敗" ); } oldflag = oldflag | flags; int ret = fcntl( fd, F_SETFL, oldflag ); if( -1 == ret ) { ERR_EXIT( "設置新的文件狀態失敗" ); } } void clear_flag( int fd, int flags ) { int oldflag; oldflag = fcntl( fd, F_GETFL, 0 ); if( -1 == oldflag ) { ERR_EXIT( "獲取原來的狀態失敗" ); } oldflag = oldflag & ~flags; int ret = fcntl( fd, F_SETFL, oldflag ); if( -1 == ret ) { ERR_EXIT( "設置新的文件狀態失敗" ); } }