看起来,可以使用 openat()
来重新打开一个已经打开的目录。例如,在我的 Linux 系统上,我可以执行以下操作:
#define _GNU_SOURCE
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
int main(void) {
int fd1 = open(".", O_PATH);
if (fd1 == -1) {
perror("open");
return 1;
}
int fd2 = openat(fd1, ".", O_RDONLY);
if (fd2 == -1) {
perror("openat");
close(fd1);
return 1;
}
close(fd1);
// do fancy things with fd2, now opened
// with access mode read-only
return 0;
}
我在任何地方都找不到这个文档,感觉有点像边缘案例。我也没有找到其他代码这样做。这是明确定义的行为吗?
编辑:更改标题:文件 -> 目录
最佳答案
这与调用 open
相同在同一个文件上两次,您可以这样做:
int fd1 = open("filename", flags1);
int fd2 = open("filename", flags2);
哪里filename
指的是现有文件(任何类型)和 flags1
和 flags2
是任何一组 O_
可以有效应用于该类型文件并且不会破坏其内容的标志。 (特别是,我们假设它们不包括 O_CREAT
、 O_TRUNC
或 O_EXCL
。)
fd1
和 fd2
将引用单独的“open file descriptions”,例如lseek
一个不会影响另一个,flock
一个会阻塞 flock
另一方面,等等。
关于c - 使用 openat 重新打开一个目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54793898/