open标志解析
open的标志并不是每1位对应一个标志,对于读写的标志,在open时必须指定一个,其宏定义如下,检查读写标志时,不能简单当使用异或,将标志与O_ACCMODE进行与操作,获取标志的低两位来确定读写标志。
/usr/include/bits/fcntl.h
#define O_ACCMODE 0003
#define O_RDONLY 00
#define O_WRONLY 01
#define O_RDWR 02
检查示例:
if((open_flag & O_ACCMODE) == O_RDONLY)
{
是否以只读的方式打开?
}
而其他的标志,每个位对应一个标志,可直接与相应标志做与运算检查标志是否被设置。
#define O_CREAT 0100 /* not fcntl */
#define O_EXCL 0200 /* not fcntl */
#define O_NOCTTY 0400 /* not fcntl */
#define O_TRUNC 01000 /* not fcntl */
#define O_APPEND 02000
#define O_NONBLOCK 04000
#define O_NDELAY O_NONBLOCK
#define O_SYNC 010000
#define O_FSYNC O_SYNC
#define O_ASYNC 020000
#ifdef __USE_GNU
#define O_DIRECT 040000 /* Direct disk access. */
#define O_DIRECTORY 0200000 /* Must be a directory. */
#define O_NOFOLLOW 0400000 /* Do not follow links. */
#define O_NOATIME 01000000 /* Do not set atime. */
#define O_CLOEXEC 02000000 /* Set close_on_exec. */
#endif
检查示例:
if(open_flag & O_EXCL)
{
检查O_EXCL是否被设置?
}
当指定O_CREAT标记时,需要给定open的第三个参数,即访问模式,可通过三个八进制数指定,也可通过一些宏指定。
#if defined __USE_MISC && defined __USE_BSD
# define S_IREAD S_IRUSR
# define S_IWRITE S_IWUSR
# define S_IEXEC S_IXUSR
#endif
#define S_IRGRP (S_IRUSR >> 3) /* Read by group. */
#define S_IWGRP (S_IWUSR >> 3) /* Write by group. */
#define S_IXGRP (S_IXUSR >> 3) /* Execute by group. */
/* Read, write, and execute by group. */
#define S_IRWXG (S_IRWXU >> 3)
#define S_IROTH (S_IRGRP >> 3) /* Read by others. */
#define S_IWOTH (S_IWGRP >> 3) /* Write by others. */
#define S_IXOTH (S_IXGRP >> 3) /* Execute by others. */
/* Read, write, and execute by others. */
#define S_IRWXO (S_IRWXG >> 3)
附:从某个目录查找包含“某一内容”的文件小技巧
find /usr/include/unistd.h | xargs grep “O_RDONLY”
在/usr/include/unistd.h查找O_RDONLY
find /usr/include/ | xargs grep “O_RDONLY
在/usr/include/目录中查找O_RDONLY