2.6.16版本开始,GNU/Linux引入opeant系统调用:

#define _XOPEN_SOURCE 700 /* Or define _POSIX_C_SOURCE >= 200809 */
#include <fcntl.h>
int openat(int dirfd , const char * pathname , int flags , ... /* mode_t mode */);
Returns file descriptor on success, or –1 on error

open相比,多了一个dirfd参数。关于它的用法,参考以下解释:

If pathname specifies a relative pathname, then it is interpreted relative to the directory referred to by the open file descriptor dirfd, rather than relative to the process’s current working directory.

If pathname specifies a relative pathname, and dirfd contains the special value AT_FDCWD , then pathname is interpreted relative to the process’s current working directory (i.e., the same behavior as open(2)).

If pathname specifies an absolute pathname, then dirfd is ignored.

总结起来,如果pathname是绝对路径,则dirfd参数没用。如果pathname是相对路径,并且dirfd的值不是AT_FDCWD,则pathname的参照物是相对于dirfd指向的目录,而不是进程的当前工作目录;反之,如果dirfd的值是AT_FDCWDpathname则是相对于进程当前工作目录的相对路径,此时等同于open。参考kernel代码则一目了然:

引入openat(及其它at结尾的函数)有以下两个原因:

First, openat() allows an application to avoid race conditions that could occur when using open(2) to open files in directories other than the current working directory. These race conditions result from the fact that some component of the directory prefix given to open(2) could be changed in parallel with the call to open(2). Such races can be avoided by opening a file descriptor for the target directory, and then specifying that file descriptor as the dirfd argument of openat().

Second, openat() allows the implementation of a per-thread “current working directory”, via file descriptor(s) maintained by the application. (This functionality can also be obtained by tricks based on the use of /proc/self/fd/dirfd, but less efficiently.)

引入openat是方便一个进程内的各线程可拥有不同的当前目录,传统的chdir会影响整个进程,而使用openat只需要每个线程在初始化时打开一个目录(调用open),然后就可以以openat在“当前目录”操作文件了,如:
int dirfd = open("/tmp"); // 相当于chdir到“/tmp”
int filefd = openat(dirfd, "myfile"); // 在/tmp目录下打开“myfile”文件

用法示例:

#include <stdio.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h> void creat_at(char *dir_path, char *relative_path)
{
int dir_fd;
int fd;
int flags;
mode_t mode; dir_fd = open(dir_path, O_RDONLY); //fd参数是通过打开相对路径名所在的目录来获取。
if (dir_fd < )
{
perror("open");
exit(EXIT_FAILURE);
} flags = O_CREAT | O_TRUNC | O_RDWR;
mode = ; //-rw-r-----
fd = openat(dir_fd, relative_path, flags, mode);
if (fd < )
{
perror("openat");
exit(EXIT_FAILURE);
} write(fd, "HELLO", ); close(fd);
close(dir_fd);
} int main()
{
creat_at("../03.文件IO", "log.txt");
return ;
}

借用dirfd,将DIR*转换成int类型的文件描述符

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <dirent.h>
#include <stdio.h>
#include <unistd.h> int main()
{
DIR *dir;
int dirfd2;
int fd;
int n; dir = opendir("../03.文件IO");
if(NULL == dir)
{
perror("open dir error");
return -;
}
dirfd2 = dirfd(dir);
if(- == dirfd2)
{
perror("dirfd error");
return -;
} fd = openat(dirfd2,"output.log",O_CREAT|O_RDWR|O_TRUNC, \
                      S_IRWXU|S_IRWXG|S_IRWXO);
if(- == fd)
{
perror("opeat error");
return -;
}
n = write(fd,"Hello world!\n",); close(fd);
closedir(dir); return ; }

参考资料:
openat(2) – Linux man page
The Linux programming interface

http://blog.csdn.net/wang1902568721/article/details/47796173

http://bbs.chinaunix.net/thread-2081442-1-1.html

openat与open的区别及用法示例的更多相关文章

  1. Linux find 用法示例

    Linux中find常见用法示例 ·find   path   -option   [   -print ]   [ -exec   -ok   command ]   {} \; find命令的参数 ...

  2. GROUP BY,WHERE,HAVING之间的区别和用法

      GROUP BY,WHERE,HAVING之间的区别和用法 分类: Oracle学习2009-11-01 23:40 21963人阅读 评论(6) 收藏 举报 mathmanagersql数据库m ...

  3. [转]Linux中find常见用法示例

    Linux中find常见用法示例[转]·find   path   -option   [   -print ]   [ -exec   -ok   command ]   {} \;find命令的参 ...

  4. oracle中to_date详细用法示例(oracle日期格式转换)

    这篇文章主要介绍了oracle中to_date详细用法示例,包括期和字符转换函数用法.字符串和时间互转.求某天是星期几.两个日期间的天数.月份差等用法 TO_DATE格式(以时间:2007-11-02 ...

  5. SQL Server连接查询之Cross Apply和Outer Apply的区别及用法(转载)

    先简单了解下cross apply的语法以及会产生什么样的结果集吧!示例表: SELECT * FROM tableA CROSS APPLY tableB 两张表直接连接,不需要任何的关联条件,产生 ...

  6. Java容器类List、ArrayList、Vector及map、HashTable、HashMap的区别与用法

    Java容器类List.ArrayList.Vector及map.HashTable.HashMap的区别与用法 ArrayList 和Vector是采用数组方式存储数据,此数组元素数大于实际存储的数 ...

  7. 转 Java中final、finally、finalize的区别与用法

    Java中final.finally.finalize的区别与用法   1.简单区别:final用于声明属性,方法和类,分别表示属性不可交变,方法不可覆盖,类不可继承.finally是异常处理语句结构 ...

  8. Position属性四个值:static、fixed、absolute和relative的区别和用法

    Position属性四个值:static.fixed.absolute和relative的区别和用法 在用CSS+DIV进行布局的时候,一直对position的四个属性值relative,absolu ...

  9. Python中内置数据类型list,tuple,dict,set的区别和用法

    Python中内置数据类型list,tuple,dict,set的区别和用法 Python语言简洁明了,可以用较少的代码实现同样的功能.这其中Python的四个内置数据类型功不可没,他们即是list, ...

随机推荐

  1. 签名/加密_Java_hutool( 01 代码实现 )

    本文档不讲解签名/加密相关的理论知识, 仅列出通过Java实现的方式. 待处理: Hutool含有很多工具的封装, 有时间需要好好研究一下(https://blog.csdn.net/moshowga ...

  2. gcc 带参数进行编译

    gcc -DYES -o helloyes hello.c 在hello.c中存在 #ifdefine YES ........

  3. mac安装需要的骚操作

    显示隐藏文件 defaults write com.apple.finder AppleShowAllFiles -bool true; KillAll Finder 允许任何来源 sudo spct ...

  4. 沙雕题目 来自luogu

    P5316 恋恋的数学题 题目描述 现在恋恋正在处理的题目十分简单:现在有k (2≤k≤4)k \space (2\leq k\leq 4)k (2≤k≤4)个数,恋恋不知道它们分别是几,只知道它们两 ...

  5. input输入框限制只能输入数字

    js: function onlyNumber(event){     var keyCode = event.keyCode;     if((keyCode<48&&keyC ...

  6. python中的匿名函数

    python 使用 lambda 来创建匿名函数. 所谓匿名,意即不再使用 def 语句这样标准的形式定义一个函数. lambda 只是一个表达式,函数体比 def 简单很多. lambda的主体是一 ...

  7. Pluck CMS 4.7.10远程代码执行漏洞分析

    本文首发于先知: https://xz.aliyun.com/t/6486 0x01漏洞描述 Pluck是用php编写的一款的小型CMS影响版本:Pluck CMS Pluck CMS 4.7.10( ...

  8. centos7 设置 防火墙 开机自启

    CentOS 7.0默认使用的是firewall作为防火墙,之前版本是使用iptables. 1.设置firewall开机启动 systemctl enable firewalld 2.禁止firew ...

  9. count(1) 与 count(*) 比较

    1.  count(1) and count(*) 当表的数据量大些时,对表作分析之后,使用count(1)还要比使用count(*)用时多了! 从执行计划来看,count(1)和count(*)的效 ...

  10. 如何配置WAMP环境(主要是Apache与PHP)

    1.配置Apache 1.编辑Apache配置文件---http.conf(位于安装目录下的conf子目录内): 2.修改Document Root 和 Directory选项,这是修改Apache的 ...