O_ACCMODE

来源:互联网 发布:seo外链发布平台 编辑:程序博客网 时间:2024/05/17 03:33

这个宏作为一个掩码以与文件状态标识值做AND位运算,产生一个表示文件访问模式的值。这模式将是O_RDONLY, O_WRONLY, 或 O_RDWR(在GNU系统中,也可能是零,并且从不包括 O_EXEC 位)
 
O_ACCMODE<0003>:读写文件操作时,用于取出flag的低2位
O_RDONLY<00>:只读打开
O_WRONLY<01>:只写打开
O_RDWR<02>:读写打开
 
#include "apue.h"
#include <fcntl.h>
int
main(int argc, char *argv[])
{
 int  val;
 if (argc != 2)
  err_quit("usage: a.out <descriptor#>");
 if ((val = fcntl(atoi(argv[1]), F_GETFL, 0)) < 0)
  err_sys("fcntl error for fd %d", atoi(argv[1]));
 switch (val & O_ACCMODE) {
 case O_RDONLY:
  printf("read only");
  break;
 case O_WRONLY:
  printf("write only");
  break;
 case O_RDWR:
  printf("read write");
  break;
 default:
  err_dump("unknown access mode");
 }
 if (val & O_APPEND)
  printf(", append");
 if (val & O_NONBLOCK)
  printf(", nonblocking");
#if defined(O_SYNC)
 if (val & O_SYNC)
  printf(", synchronous writes");
#endif
#if !defined(_POSIX_C_SOURCE) && defined(O_FSYNC)
 if (val & O_FSYNC)
  printf(", synchronous writes");
#endif
 putchar('/n');
 exit(0);
}
/usr/include/fcntl.h中包含了bits/fcntl.h,且在bits/fcntl.h中定义了O_ACCMODE
/* open-only flags */#define O_RDONLY 0x0000 /* open for reading only */#define O_WRONLY 0x0001 /* open for writing only */#define O_RDWR 0x0002 /* open for reading and writing */#define O_ACCMODE 0x0003 /* mask for above modes */#if __BSD_VISIBLE#define FREAD 0x0001#define FWRITE 0x0002#endif#define O_NONBLOCK 0x0004 /* no delay */#define O_APPEND 0x0008 /* set append mode */#if __BSD_VISIBLE#define O_SHLOCK 0x0010 /* open with shared file lock */#define O_EXLOCK 0x0020 /* open with exclusive file lock */#define O_ASYNC 0x0040 /* signal pgrp when data ready */#define O_FSYNC 0x0080 /* synchronous writes */#endif#define O_SYNC 0x0080 /* POSIX synonym for O_FSYNC */#if __BSD_VISIBLE#define O_NOFOLLOW 0x0100 /* don't follow symlinks */#endif#define O_CREAT 0x0200 /* create if nonexistent */#define O_TRUNC 0x0400 /* truncate to zero length */#define O_EXCL 0x0800 /* error if already exists */#ifdef _KERNEL#define FHASLOCK 0x4000 /* descriptor holds advisory lock */#endif/* Defined by POSIX 1003.1; BSD default, but must be distinct from O_RDONLY. */#define O_NOCTTY 0x8000 /* don't assign controlling terminal */#if __BSD_VISIBLE/* Attempt to bypass buffer cache */#define O_DIRECT 0x00010000#endif