#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( "设置新的文件状态失败" );
}
}