使用fcntl获取文件状态标志,修改之后再设置回去
不能只是执行 F_SETFD 或者 F_SETFL,这样会关闭以前设置的标志位
#include <apue.h>
#include <errno.h>
#include <fcntl.h>
#define BUFSIZE 4096
int main(void)
{
char buf[BUFSIZE];
/*
* enable to write synchronously
* to avoid missing data while the
* system ecounter an error or exception
* */
set_fl(STDOUT_FILENO, O_SYNC);
while(1) {
if (read(STDIN_FILENO, buf, BUFSIZE) == BUFSIZE)
write(STDOUT_FILENO, buf, BUFSIZE);
else {
fprintf(stderr, "%s", strerror(errno));
exit(EXIT_FAILURE);
}
}
}
/*
* us fcntl() to set the flags
* you should get the flags first
* then to change the flags
*/
void set_fl(int fd, int flags)
{
int val;
if ((val = fcntl(fd, F_GETFL, 0)) < 0) {
fprintf(stderr, "%s", strerror(errno));
exit(EXIT_FAILURE);
}
/* turn on the flags */
val |= flags;
//to move off you should type: val &= ~flags;
if (fcntl(fd, F_SETFL, val) < 0) {
fprintf(stderr, "%s", strerror(errno));
exit(EXIT_FAILURE);
}
}
使用 fcntl 打印文件标志符
#include<apue.h>
#include<fcntl.h>
int main( int argc, char *argv[] )
{
int val;
printf("%d, %s, %s \n\n", argc, argv[0], argv[1] );
if( argc != 2 )
printf("usage: a.out <descriptor#>");
if( (val = fcntl( atoi(argv[1]), F_GETFL, 0 )) < 0 ) // 0 is O_RDONLY
printf("fcntl error for fd : %d\n", atoi(argv[1]) );
switch( val & O_ACCMODE ){ //use O_ACCMODE to gain the visit
case O_RDONLY :
printf("read only\n");
break;
case O_WRONLY :
printf("write only\n");
break;
case O_RDWR :
printf("read write\n");
break;
default :
printf("unknown access mode\n");
}
if( val & O_APPEND )
printf("append\n");
if( val & O_NONBLOCK )
printf("nonblocking\n");
if( val & O_SYNC )
printf("synchronous writes\n");
#if !defined( _POSIX_C_SOURCE ) && defined( O_FSYNC ) && ( O_FSYNC != O_SYNC )
if( val & O_FSYNC )
printf("synchronous writes\n");
#endif
putchar('\n');
exit( 0 );
}