openat与open的区别及用法示例
从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_FDCWD,pathname则是相对于进程当前工作目录的相对路径,此时等同于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的区别及用法示例的更多相关文章
- Linux find 用法示例
Linux中find常见用法示例 ·find path -option [ -print ] [ -exec -ok command ] {} \; find命令的参数 ...
- GROUP BY,WHERE,HAVING之间的区别和用法
GROUP BY,WHERE,HAVING之间的区别和用法 分类: Oracle学习2009-11-01 23:40 21963人阅读 评论(6) 收藏 举报 mathmanagersql数据库m ...
- [转]Linux中find常见用法示例
Linux中find常见用法示例[转]·find path -option [ -print ] [ -exec -ok command ] {} \;find命令的参 ...
- oracle中to_date详细用法示例(oracle日期格式转换)
这篇文章主要介绍了oracle中to_date详细用法示例,包括期和字符转换函数用法.字符串和时间互转.求某天是星期几.两个日期间的天数.月份差等用法 TO_DATE格式(以时间:2007-11-02 ...
- SQL Server连接查询之Cross Apply和Outer Apply的区别及用法(转载)
先简单了解下cross apply的语法以及会产生什么样的结果集吧!示例表: SELECT * FROM tableA CROSS APPLY tableB 两张表直接连接,不需要任何的关联条件,产生 ...
- Java容器类List、ArrayList、Vector及map、HashTable、HashMap的区别与用法
Java容器类List.ArrayList.Vector及map.HashTable.HashMap的区别与用法 ArrayList 和Vector是采用数组方式存储数据,此数组元素数大于实际存储的数 ...
- 转 Java中final、finally、finalize的区别与用法
Java中final.finally.finalize的区别与用法 1.简单区别:final用于声明属性,方法和类,分别表示属性不可交变,方法不可覆盖,类不可继承.finally是异常处理语句结构 ...
- Position属性四个值:static、fixed、absolute和relative的区别和用法
Position属性四个值:static.fixed.absolute和relative的区别和用法 在用CSS+DIV进行布局的时候,一直对position的四个属性值relative,absolu ...
- Python中内置数据类型list,tuple,dict,set的区别和用法
Python中内置数据类型list,tuple,dict,set的区别和用法 Python语言简洁明了,可以用较少的代码实现同样的功能.这其中Python的四个内置数据类型功不可没,他们即是list, ...
随机推荐
- 题解 [NOIP2015]运输计划
题解 [NOIP2015]运输计划 题面 解析 首先肯定是要求出每条路径的长度. 这个用节点到根的前缀和就行了(一开始脑抽写了个线段树...) 然后有一个显然的类似贪心的想法, 就是你改造的边肯定在最 ...
- Linux 安装python3.7
首先需要安装依赖 yum -y install zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-dev ...
- Codeforces Round #598 (Div. 3) A,B,C,D{E,F待补}
A. Payment Without Change #include<bits/stdc++.h> using namespace std; #define int long long ...
- Oracle 物理结构(五) 文件-在线日志文件
一.什么是在线日志文件 默认情况下redo的块大小是磁盘的扇区大小,通常是512字节,但是现在很多磁盘开始支持4k的扇区,oracle能自动识别并使用4k的大小,但是使用4k的redo block会有 ...
- ueditor+粘贴word
Chrome+IE默认支持粘贴剪切板中的图片,但是我要发布的文章存在word里面,图片多达数十张,我总不能一张一张复制吧?Chrome高版本提供了可以将单张图片转换在BASE64字符串的功能.但是无法 ...
- 蓝牙4.0模块,AT指令集
一,LED状态 二,蓝牙模块有两种通信模式 1,AT指令模式 2,数据透传模式 三.AT指令程序设计 1.设置模块的名字 void usart3_send_str(char *pbuf) { whil ...
- 2018年 第43届ACM-ICPC亚洲区域赛(青岛)现场赛 赛后总结
下了动车后,又颠颠簸簸的在公交车上过了接近一个小时,本来就晕车,于是,到的时候脑子晕死了,而且想吐.可能是没吃早饭的缘故,午饭好好次QWQ. 开幕式 还是第一次在这种环境下参赛,记得以前是看老师发的学 ...
- 使用appium+python做UI自动化的demo
使用appium+python做UI自动化的demo 案例使用的知乎app,下载最新的知乎apk,存在了电脑上,只需要配置本机上app目录,不需要再配置appPackage和appActivity # ...
- tp中打印sql,查看语句信息
$a = self::where($where)->fetchSql(true)->select(); dump($a);
- ionic serve 报【ionic-app-scripts' 不是内部或外部命令 】问题解
Error: Cannot find module 'E:\angular\ionic0515\node_modules\@ionic\app-scripts' at Function.Modu ...
